With this structure definition:
struct word {
char *cont; //content of the word
char *wsp; //whitespace following the word
int ctr;
};
for a word, I’m trying to write a function to get the first word from stdin with all the whitespace following it. Here it is:
struct word *getword(){
char cont[WORDLIM];
char wsp[WORDLIM];
cont[0] = '\0';
wsp[0] = '\0';
if (peekchar() == EOF) return NULL; //peekchar defined elsewhere as getting a char and ungetc-ing it
REPEAT{ //macro for for(;;)
char c = getchar();
char buf[2];
buf[0]=c;
buf[1]='\0';
if (c == '\n' || c == ' '){
strcat(wsp, buf);
if (peekchar() != '\n' && peekchar() != ' '){
struct word *toret;
toret = malloc(sizeof(struct word));
toret->cont = cont;
toret->wsp = wsp;
toret->ctr = -1;
printf("---%s---\n", toret->wsp); //just for debugging
return toret;
}
continue;
}
}
printf("PANIC PANIC PANIC THIS IS GOING WROOOOONG!!!!!\n");
return NULL;
}
Now the fun thing is that I can get the correct output of whitespace in the just for debugging line, but when I attempt to access getword()->wsp, I get random garbage. Even more interestingly, getword()->cont works…
I’m a really new newbie to C…what did I do wrong?
Lose that macro post-haste. Using the preprocessor to de-uglify C syntax is a recipe for heartburn. Just use
for(;;)orwhile(1). The compiler is usually smart enough to turn it into an unconditional jump.As for your problem:
The
contandwsparrays are declared locally to thegetwordfunction; once the function exits, the arrays cease to exist, and any pointers to them are no longer valid. What you’ll need to do is allocate memory for thecontandwspmembers oftoretin addition to the memory fortoretitself.Note that when you need to free the memory for the struct, you’ll first need to free the memory for the
contandwspmembers.