我正在尝试使用链表创建一个缓冲队列。我使用pthread作为一个生成线程和多个读取线程。我的程序正确地使用pthread打开一个文件,并开始将文件中的行读入char plain_text120;并添加一个空字符,然后将该参数传递给以下函数。
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;
}
}使用的结构如下:
struct queue_node
{
char* password;
struct queue_node *next_node;
};我的代码运行了大约2000个单词,然后用SegFault击中了我。
GDB,其中,生成以下内容:
来自/usr/lib/libc.so.6的_int_malloc ()中的0 0x00007ffff71a3118
1来自/usr/lib/libc.so.6的malloc ()中的1 0x00007ffff71a43d4
2 0x00000000004017cd在main.c:217的入队(word=0x7ffff6d0deb0 "!!626Ru")中
3 0x0000000000401779,位于main.c:195的Dictionary_fill (arg=0x7fffffffeba5)中
4来自/usr/lib/libpthread.so.0的start_thread ()中的4 0x00007ffff74d44a4
5来自/usr/lib/libc.so.6的clone ()中的5 0x00007ffff721213d
我猜我用malloc分配错误了,但我已经找了几天了,头撞在墙上,似乎就是找不到。
发布于 2015-10-21 13:47:30
这是错误的:
new_node->word = malloc(sizeof(strlen(word)+1));你不希望sizeof在其中,否则你没有为你的字符串分配足够的存储空间。
当然应该是:
new_node->word = malloc(strlen(word)+1);发布于 2015-10-21 13:47:57
new_node->word = malloc(sizeof(strlen(word)+1));不要在这里使用sizeof。只需要写-
new_node->word = malloc(strlen(word)+1);在这里,您将内存分配给new_node->word,因此检查它的NULL -
if(new_node->password == NULL)去看看这个-
if(new_node->word== NULL)https://stackoverflow.com/questions/33251779
复制相似问题