Isolated a segfault - but why is it happening?
Using the DevC++ debugger (still new to it), I'm pretty sure I've isolated a segfault scenario, but I've got no idea why it's happening.
void LinkedList::Add(const char *Word){
ListNode *newNode = new ListNode;
strcpy(newNode->Word, Word);
newNode->Next = NULL;
...
}
A segfault occurs at the "newNode->Next = NULL;". However if I开发者_开发百科 remove the strcpy above it, the segfault does not occur (but it means my newNode->Word is empty)
EDIT: sorry guys, here is the ListNode:
struct ListNode
{
char *Word;
LNodePtr Next;
};
If the Word
member is a pointer, your strcpy
will overwrite unallocated memory.
After that, most operations can fail.
Using std::string
instead of const char*
will save you in many places.
You have not allocated any memory for Word
pointer in the ListNode
structure. Without this, it is pointing to some random location and whenever you are trying to write to that location (using strcpy
) you will get an access violation. The simplest way to solve this is to use the std::string
class and get rid of all manual memory management.
If you really want to use char*
, then write a constructor for ListNode
which takes const char*
parameter (remember to declare it as explicit
though) and use the strlen
to find the length of the input string. Then allocate len + 1
(extra one char
for the NULL terminator) characters and store the address in Word
pointer. After that you can do strncpy
.
strcpy
is fine but very dangerous, it make a copy of your chars until it reaches a \0
. If your Word
do not contain any \0, it will copy a lot of stuff into you newNode->Word
pointer.
The other potential danger is the way you initialize the newNode->Word
, did you allocate enough room to make the string copy?
throwing a guess out there.. I'd hazard that in your ListNode
implementation, Word
is a char*
, and it's not initialized to point to a valid block of memory (could be null) - strcpy()
does not automatically allocate space, it assumes there is enough space at the destination. And here, it's trying to copy the string to a null pointer (or uninitialized pointer) - hence the segfault...
精彩评论