Reputation: 2218
I keep constantly getting a segmentation error with a small portion of code and I have no idea why, I'm using malloc and cant see any reason with that, just as soono as it hits the portion of data, its crashes. The Data is:
listNode* node = (listNode*)malloc(sizeof(listNode)); <-This is the Line
strcpy(node->entry, string);
node->next = NULL;
Using the struct definition:
typedef struct
{
char* entry;
struct listNode* next;
}listNode;
The data does get freed at one point, however it cannot reach said point. Thanks for the help!
Upvotes: 0
Views: 367
Reputation: 233
You are not allocating allocate memory for the entry pointer. as while allocationg structure just 4 bytes allocated for *entry pointer you should do
listNode* node = (listNode*)malloc(sizeof(listNode)); // allocate memory for structure node->entry = malloc(strlen(string) + 1);// allocate memory for string strcpy(node->entry, string); //copying strings
now it will run fine
Upvotes: 0
Reputation: 14458
Are you sure you're crashing on the malloc
call? It's much more likely that you're crashing on the strcpy
. In fact, the strcpy
in this case is almost guaranteed to cause bad behavior, although to be precise the behavior is undefined.
The malloc
should succeed as long as you haven't filled up your heap. However, because you called malloc
and not calloc
, you have no guarantees about the contents of node->entry
. The C standard doesn't define what is stored in memory allocated with malloc
, so node->entry
is filled with garbage. By trying to copy to a bad pointer, your app is crashing for attempting to accessing an incorrect memory address.
Alexey Frunze is 100% correct on the fix - malloc
space and change node->entry
to point at the newly allocated memory, then copy string
into node->entry
. This avoids undefined behavior for using an uninitialized pointer, as I described in another SO answer.
Upvotes: 2
Reputation: 62048
You didn't allocate memory for the entry
pointer. You're trying to copy your string
to a bogus location specified by the uninitialized pointer entry
. You might do this instead:
node->entry = malloc(strlen(string) + 1);
strcpy(node->entry, string);
Upvotes: 1