C 为什么指针赋值后会出现分段错误?
在指针赋值后立即调用函数时,我遇到了一个分段错误C 为什么指针赋值后会出现分段错误?,c,pointers,segmentation-fault,C,Pointers,Segmentation Fault,在指针赋值后立即调用函数时,我遇到了一个分段错误 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
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
,它可以正常工作。
是因为这两个指针的大小不同吗?
MSG1
和MSG
是不同的类型
pMsg1
指向Msg
,其类型为Msg
,但类型为MSG1*
当试图从
MSG1
中访问存储区中的字段时,会出现未定义的行为。如果结构不相同,则不要通过赋值进行复制
pMsg1 = (MSG1 *)&Msg;
将结构复制到单个元素中。然后它解决了u r问题。只有当一个结构位于另一个结构的开头时,才能安全地将一个结构指针转换为另一个(无论大小,请参见C标准):
typedef结构{
INTA;
}S1;
类型定义结构{
S1;//您应该提供更多的信息。例如:您在Recv\u msg
中做什么?源代码。请显示更多的代码。确保所有指针(包括结构内部的指针)当被撤销时,被初始化,而不是代码> null < /代码>。考虑也使用<代码> Valgnnd<代码>来追查内存泄漏错误。您需要更多的信息来让其他人开始诊断。将线程id作为第一个参数。你确定pMsg1->…是一个真正的线程id吗?为什么会导致segfault?它仍然是一个有效的指针地址。它会导致segfault,因为pthread\u join
试图理解它在该地址找到的数据,但这是胡说八道。不过,它不会在指针分配上产生segfault。当您在调用pthread_join()时访问“pMsg1->”时,它的segfaulting问题有以下详细信息:MSG的大小为1040字节,sizeof(MSG1)..
部分的某些内部访问。
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