1

I'm using GDB to go through my code and each time the while loop is entered, the values in NameList[] change. Like I set NameList[0] to chr2, but when I go back through the while loop in gdb, I say x/s NameList[0] and now it's set to the new value of chr2! How is this able to happen? I know I'm changing the pointer, but shouldn't the array be storing the old value of the pointer and not be allowed to update?

while (fgets(thisline, length, input) != NULL) {
    chr = strtok(Line, "    ");
    if(chr != NULL) {
        chr2 = strtok(chr, " ")
        int j = 0;
        while(NameList[j] != NULL) {
            j++;
        }
        NameList[j] = chr2;
    }
}

1 Answer 1

1

Try changing

    NameList[j] = chr2;

to

    NameList[j] = strdup(chr2);

And see what happens. The issue is that you are just storing a pointer to the char array, and that char array is changing out from under you. The strdup function copies the whole array.

Sign up to request clarification or add additional context in comments.

1 Comment

@user3002440 But don't forget to free() it after use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.