pthread malloc SegFault

时间:2015-10-21 05:44:52

标签: c multithreading

我正在尝试使用链接列表创建缓冲区队列。我正在使用pthreads生成线程和多个读取线程。我的程序正确使用pthread打开文件并开始读取文件的行到char plain_text [120];并添加一个空字符,然后将该参数传递给以下函数。

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

来自/usr/lib/libc.so.6的malloc()中的0x00007ffff71a43d4

2 0x00000000004017cd in enqueue(word = 0x7ffff6d0deb0“!! 626Ru”)     在main.c:217

Dictionary_fill中的

3 0x0000000000401779(arg = 0x7fffffffeba5)     在main.c:195

来自/usr/lib/libpthread.so.0的start_thread()中的

4 0x00007ffff74d44a4

来自/usr/lib/libc.so.6的clone()中的0x00007ffff721213d

我猜我是不正确地分配了malloc,但是我已经搜索并将我的头撞在墙上几天了,似乎无法弄明白。

2 个答案:

答案 0 :(得分:2)

这是错误的:

new_node->word = malloc(sizeof(strlen(word)+1));

你不希望sizeof在那里,否则你没有为你的字符串分配足够的存储空间。

当然应该是:

new_node->word = malloc(strlen(word)+1);

答案 1 :(得分:1)

 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)
相关问题