Reputation: 66
I am trying to create a buffer queue using a linked list. I am using pthreads for a generating thread and multiple reading threads. My program correctly uses a pthread to open a file and start reading lines of the file into char plain_text[120]; and adds a null character, which then passes that parameter into the following function.
void enqueue(char word[])
{
struct queue_node *new_node = malloc(sizeof(struct queue_node));
if(new_node == NULL)
{
printf("Failed to allocate memory in enqueue\n");
exit(-1);
}
new_node->word = malloc(sizeof(strlen(word)+1));
if(new_node->password == NULL)
{
printf("Failed to allocate memory in enqueue for the password\n");
exit(-1);
}
strcpy(new_node->word, word);
new_node->next_node = NULL;
enqueued++;
if(head==NULL)
{
head = new_node;
previous_node = head;
current_node = head;
deleting_node = head;
}
else
{
previous_node->next_node = new_node;
previous_node = previous_node->next_node;
}
}
The struct used is this:
struct queue_node
{
char* password;
struct queue_node *next_node;
};
My code runs for about 2000 words and then hits me with a SegFault.
GDB where, produces this:
0 0x00007ffff71a3118 in _int_malloc () from /usr/lib/libc.so.6
1 0x00007ffff71a43d4 in malloc () from /usr/lib/libc.so.6
2 0x00000000004017cd in enqueue (word=0x7ffff6d0deb0 "!!626Ru") at main.c:217
3 0x0000000000401779 in Dictionary_fill (arg=0x7fffffffeba5) at main.c:195
4 0x00007ffff74d44a4 in start_thread () from /usr/lib/libpthread.so.0
5 0x00007ffff721213d in clone () from /usr/lib/libc.so.6
I am guessing that I am improperly allocating with malloc, but I have searched and banged my head against the wall for a few days now and just can't seem to figure it out.
Upvotes: 0
Views: 475
Reputation: 16607
new_node->word = malloc(sizeof(strlen(word)+1));
Don't use sizeof
here . Just write -
new_node->word = malloc(strlen(word)+1);
And in this you allocate memory to new_node->word
so check it for NULL
-
if(new_node->password == NULL)
Check this instead-
if(new_node->word== NULL)
Upvotes: 1
Reputation: 212979
This is wrong:
new_node->word = malloc(sizeof(strlen(word)+1));
You don't want sizeof
in there, otherwise you are not allocating enough storage for your string.
It should of course be:
new_node->word = malloc(strlen(word)+1);
Upvotes: 2