mutex_init()会导致奇怪的段错误

时间:2013-03-26 19:13:42

标签: c multithreading pthreads mutex

我试图处理posix线程时遇到一个奇怪的问题。 我将从代码开始:

#include <pthread.h>
#include <semaphore.h>


typedef struct {
    pthread_mutex_t *mutex; 
} buffer_t;


buffer_t *buffer_alloc(unsigned int maxSize) {

    buffer_t *buffer = (buffer_t *) malloc(sizeof(buffer_t));
    if(buffer == NULL)
        return NULL;

    pthread_mutex_init(buffer->mutex, NULL); // This line causes a crash

    pthread_mutex_t *mutex;
    pthread_mutex_init(mutex, NULL); // This one doesn't

}

我在第一个pthread_mutex_init()上遇到了细分错误。 这是gdb的runlog和backtrace:

[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".


Program received signal SIGSEGV, Segmentation fault.
__pthread_mutex_init (mutex=0x0, mutexattr=0x0) at pthread_mutex_init.c:83
83  pthread_mutex_init.c: No such file or directory.

(gdb) backtrace
#0  __pthread_mutex_init (mutex=0x0, mutexattr=0x0) at pthread_mutex_init.c:83
#1  0x00000000004015a8 in buffer_alloc (maxSize=10) at buffers.c:26

感谢您的帮助!

3 个答案:

答案 0 :(得分:4)

将结构定义更改为:

typedef struct {
    pthread_mutex_t mutex; 
} buffer_t;

然后将互斥锁初始化为:

pthread_mutex_init(&buffer->mutex, NULL);

在这两种情况下,您的代码都使用了未初始化的指针。在第二种情况下不会(立即)导致分段错误,纯粹是运气,它可能会破坏某些变量并在以后造成麻烦。

答案 1 :(得分:2)

您传递给pthread_mutex_init()的指针未初始化,它不指向已分配的内存,因此您的程序会调用未定义的行为。您可以做的是修改结构或buffer_alloc()函数以显式为互斥锁分配内存。 I. e。,解决方案#1(我更喜欢这个):

typedef struct {
    pthread_mutex_t mutex;
} buffer_t;

buffer_t *buffer_alloc(unsigned int maxSize)
{
    buffer_t *buffer = malloc(sizeof(*buffer));
    if (buffer == NULL)
        return NULL;

    pthread_mutex_init(&buffer->mutex, NULL);

    // etc.
    return buffer;
}

解决方案#1,动态分配:

typedef struct {
    pthread_mutex_t *mutex;
} buffer_t;

buffer_t *buffer_alloc(unsigned int maxSize)
{
    buffer_t *buffer = malloc(sizeof(*buffer));
    if (buffer == NULL)
        return NULL;

    buffer->mutex = malloc(sizeof(*(buffer->mutex)));
    if (buffer->mutex == NULL) {
        free(buffer);
        return NULL;
    }

    pthread_mutex_init(buffer->mutex, NULL);

    // etc.
    return buffer;
}

在后一种情况下,不要忘记free()互斥体以及“析构函数”。

另外,don't cast the return value of malloc()

答案 2 :(得分:0)

你传入了一个未初始化的缓冲区....你已经分配了buffer_t,但是将其初始化为空。所以互斥指针是指向谁知道在哪里的随机值。

然后,pthread_mutex_init需要指向实际存在的互斥锁的指针。你传给它一个指向随机记忆的指针。

看看这不能解决它......

typedef struct {
    pthread_mutex_t mutex; 
} buffer_t;


buffer_t *buffer_alloc(unsigned int maxSize) {

    buffer_t *buffer = (buffer_t *) malloc(sizeof(buffer_t));
    if(buffer == NULL)
        return NULL;

    pthread_mutex_init(&buffer->mutex, NULL); // This line causes a crash