pthread_rwlock_init() 导致分段错误
我怀疑我在这里做了一些愚蠢的事情,但是当我尝试在嵌入结构中的 rwlock 上运行 pthread_rwlock_init() 时,我在嵌入式 Linux 平台(GCC 编译器)上遇到了 seg 错误。
struct rwlock_flag {
int flag; // Flag
pthread_rwlock_t * rwlock; // Reader/writer lock for flag
};
以下内容会导致段错误...
struct rwlock_flag * running;
running = (struct rwlock_flag *) malloc (sizeof(struct rwlock_flag));
rslt = pthread_rwlock_init(running->rwlock, NULL);
与此一样...
pthread_rwlock_t * rwlock_dg2;
pthread_rwlock_init(rwlock_dg2,NULL);
但是以下内容工作正常...
pthread_rwlock_t rwlock_dg;
pthread_rwlock_init(& rwlock_dg,NULL);
有什么想法吗?
I suspect I am doing something dumb here but I am getting seg faults on an embedded Linux platform (GCC compiler) when I try to run pthread_rwlock_init() on a rwlock embedded in a structure.
struct rwlock_flag {
int flag; // Flag
pthread_rwlock_t * rwlock; // Reader/writer lock for flag
};
The following causes a seg fault...
struct rwlock_flag * running;
running = (struct rwlock_flag *) malloc (sizeof(struct rwlock_flag));
rslt = pthread_rwlock_init(running->rwlock, NULL);
As does this...
pthread_rwlock_t * rwlock_dg2;
pthread_rwlock_init(rwlock_dg2,NULL);
However the following works fine...
pthread_rwlock_t rwlock_dg;
pthread_rwlock_init(& rwlock_dg,NULL);
Any thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的第一个和第二个案例都尝试初始化 rwlock 以获取指向任何地方的指针(好吧,从技术上讲,指向随机或 NULL 位置)。
在第一种情况下,您为包装器结构分配空间,但不为其中的
pthread_rwlock_t*
分配空间。因此它将指向一个随机位置。这适用于实际的 pthread_rwlock_t 而不是指向 pthread_rwlock_t 的指针:
在第二个中,类似地,rwlock_dg2 没有后备存储,因此它要么指向随机位置(如果在函数内分配)或 NULL(如果在文件级别声明)。您需要:
您的第三个案例之所以有效,是因为指针
&rwlock_dg
实际上指向一个真正的pthread_rwlock_t
(当然是rwlock_dg
>)。Your first and second cases both try to initialise the rwlock for a pointer that points nowhere (well, technically, to a random or NULL location).
In the first case, you allocate space for your wrapper structure but not the
pthread_rwlock_t*
within it. Hence it would point to a random location.This would work with an actual
pthread_rwlock_t
rather than a pointer to one:In the second, similarly, there's no backing storage for
rwlock_dg2
so it either points to a random location (if allocated within a function) or NULL (if declared at file level). You need:Your third case, which works, does so because the pointer
&rwlock_dg
actually points to a realpthread_rwlock_t
(which is of courserwlock_dg
).