-
wierd struct error
Hi,
I was reading a text file,and storing each word in a struct:
Code:
typedef struct WordNode{
struct wordNode *nextWord;
char *word; //store the word
int whiteSpaces; //num of spaces between words
}wordNode;
and i got a function makeWordNode function to create a word node
Code:
wordNode *makeWordNode(char* string,int numSpaces){
wordNode *newWordNode;
newWordNode=(wordNode*)malloc(sizeof(wordNode));
strcpy(newWordNode->word,string);
newWordNode->whiteSpaces=numSpaces;
newWordNode->nextWord=NULL;
printf("#%s->%d#",newWordNode->word,newWordNode->whiteSpaces);
return newWordNode;
}
interesting this code wont work and crashes.so i added printing of # char to check where the code hangs:
Code:
wordNode *makeWordNode(char* string,int numSpaces){
wordNode *newWordNode;
newWordNode=(wordNode*)malloc(sizeof(wordNode)); printf("#");
strcpy(newWordNode->word,string);
newWordNode->whiteSpaces=numSpaces;
newWordNode->nextWord=NULL;
printf("#%s->%d#",newWordNode->word,newWordNode->whiteSpaces);
return newWordNode;
}
Interestingly the 2nd version works fine and prints correct output.I cant figure out the reason for this wierd error.
help me!! Thanks
-
Where do you allocate space for 'newWordNode->word' before you strcpy to it?
-
yaah..!!!!........ memory has not been allocated
-
Could you post the whole code? Then , maybe I can see , what you could not. Maybe.
-
Thanks for helping out.no memory allocation is the main problem.But I wonder how come the 2nd code worked as it didn't have memory allocation.
-
> But I wonder how come the 2nd code worked as it didn't have memory allocation.
Sometimes, despite your best efforts to screw things up, the code still manages to do what you expect without crashing.
On other occasions, you get absolutely no margin at all for error. Even very minor mistakes can be punished harshly.
It's just Murphy at work. You just have to learn to not equate "working" with "bug free".