0

I'm blocking on a weird issue trying to deal with posix threads. I'll start with the code:

#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

}

I'm getting a segmentation fault on the first pthread_mutex_init(). Here's gdb's runlog and 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

Thanks for your help !

4

3 回答 3

4

将您的结构定义更改为:

typedef struct {
    pthread_mutex_t mutex; 
} buffer_t;

然后将互斥体初始化为:

pthread_mutex_init(&buffer->mutex, NULL);

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

于 2013-03-26T19:17:13.277 回答
2

您传递给的指针pthread_mutex_init()未初始化,它不指向分配的内存,因此您的程序会调用未定义的行为。你可以做的是修改你的结构或buffer_alloc()函数来显式地为互斥体分配内存。即,解决方案#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()“析构函数”中的互斥锁。

另外,不要强制转换malloc().

于 2013-03-26T19:19:02.557 回答
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
于 2013-03-26T19:18:23.233 回答