Please help, don't know why program is crashing...???

I am reading in values from a file, and am not sure what's wrong with my code? My main issue is within the area in bold, can anyone tell me what's wrong?

Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
void createList(intNode*& intList)
{
    intNode* lastInt; //points to last integer in file
    lastInt = NULL;
    int fileInt; //int read from input file
    ifstream intInputFile;

    intInputFile.open("intInput.txt");
    if (intInputFile.is_open())
    {
        cout << "intInput.txt open successful" << endl;
    }
    else
    {
        cout << "intInput.txt open unsuccessful" << endl;
    }
    intInputFile >> fileInt;
    while(!intInputFile.eof())
    {
        intNode* anotherInt;
        anotherInt = new intNode;
        if(intList==NULL)
        {
            intList = anotherInt;
            lastInt = anotherInt;
        }
        else
        {
            lastInt->nextNode = anotherInt;
        }
        lastInt = lastInt->nextNode;
        lastInt->intValue = fileInt;
        lastInt->nextNode = NULL;
        intInputFile >> fileInt;
    }
    intInputFile.close();
    cout << "List created from input file" << endl;
}


On the first iteration you set lastInt to anotherInt. lastInt->nextNode is presumably a null or invalid pointer. Then, rather than storing fileInt (which by the way the loop doesn't even touch, nor does it touch intInputFile) in lastInt->intValue, you move lastInt to the next node, which isn't guaranteed to exist, and assign to that the integer.
The first time the loop runs:

- anotherInt gets created. (line 21)
- intLast gets set to anotherInt (line 24)
- lastInt gets set to anotherInt (line 25)
- lastInt gets set to anotherInt->nextNode (line 31 -- PROBLEM)

This is a problem because you never initialized anotherInt->nextNode. Depending on what you're doing in intNode's constructor, you're either dereferencing a null pointer (bad), or dereferencing an uninitialized pointer (worse). Each have potential to crash.


It seems to me that line 31 should be inside the else clause.
Last edited on
Thanks. I'm confused as to how to fix it, I've tried intializing lastInt->nextNode to null but it still doesn't work. Can you explain how I would fix the problem?
Topic archived. No new replies allowed.