gpt4 book ai didi

c - 为什么在指针赋值后会出现段错误?

转载 作者:行者123 更新时间:2023-11-30 18:59:38 24 4
gpt4 key购买 nike

在指针赋值后立即调用函数时,我遇到了段错误。

typedef struct
{
DMINT field1;
DMINT field2;
DMINT field3;
} MSG1;

typedef struct
{
....
} MSG;

/* MSG is size of 1040 byte, bigger than MSG1 in size */

int main()
{
MSG Msg;
MSG1 *pMsg1;
int mid;
pthread_t tid;
...

Recv_msg( mid, &Msg); /* this function does a memcpy to &Msg */
pMsg1 = (MSG1 *)&Msg;

//ret = pthread_join(pMsg1->..... ); /* Got Segmentation fault here by GDB*/
/* even the first argument has nothing to do with pMsg1, SEGV is still received */
ret = pthread_creat(&tid, NULL, thread_function, NULL); /* Got Segmentation fault here by GDB*/

如果我删除pMsg1 = (MSG1 *)&Msg,它就可以正常工作。是因为两个指针的大小不同吗?

最佳答案

只有当一个结构体位于另一个结构体的开头时,您才可以安全地将一个结构体指针转换为另一个结构体指针(无论它们的大小如何,请参阅 C 标准。):

typedef struct {
int a;
} S1;
typedef struct {
S1 s1; // <- s1 it the FIRST structure field
int b;
} S2;
S2 s2;
S1 *s1;
s1= (S1*)&s2; // <- safe

否则您可能会陷入协调问题和未定义行为的境地。

关于c - 为什么在指针赋值后会出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9563889/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com