I am writing a program and have the following loop:
while ((c = getchar()) != EOF){
if (c == '\n'){
char newword[strlen(word) + 1];
strcpy(newword, word);
words[i].key = newword;
memset(word, '\0', MAXLENGTH);
i++;
j = 0;
} else {
word[j++] = c;
}
}
Where words is an array of structures:
struct kvp{
char *key;
int line;
};
and word is a big array (of size MAXLENGTH), the first few values of which constitute a string.
The problem rests with words[i].key. Within the if statement, printing it (after setting it to newword) will return the correct value, namely, an minimally-sized string that is the same as the word that was entered. Once the if statement is exited and we’re back in the outer body of the while loop, however, it changes to something completely random, i.e. ?HBk?.
There are three things I suspect could be happening:
strcpydoesn’t act the way I think it doesnewwordis a local variable and that somehow affects things (doesn’t sound right)- I don’t properly understand pointers or structures yet (entirely possible, I’ve just started learning C)
What is going on?
When you declare
newwordin theifblock, it goes out of scope after that block exits. If you want it to persist, you’ll need to either allocate memory in an outer scope, or allocate the string on the heap withmalloc.Note that now you’ll need to call
freeon this alloc’d block, or create a memory leak. At some later point you’ll need to callfree(words[i].key).Martin’s suggestion of using
strdupis a good one, itstrdupis available: it will do the alloc for you – but you’ll still need tofreelater.