使用sizeof分配是否会为结构指针生成错误的大小?

使用valgrind读取这个我得到:无效的写入/读取大小4

struct Person{ char* name; int age; }; struct Person* create_person(char *name, int age) { struct Person* me = (struct Person*)malloc(sizeof(struct Person*)); assert(me!= NULL); //make sure that the statement is not null me->name = name; me->age = age; return me; } 

使用这个用valgrind得到干净的日志

 struct Person{ char* name; int age; }; struct Person* create_person(char *name, int age) { struct Person* me = (struct Person*)malloc(sizeof(struct Person*)+4); assert(me!= NULL); //make sure that the statement is not null me->name = name; me->age = age; return me; } 

为什么我应该显式地使用sizeof(struct+intSize)来避免这个错误? sizeof不能得到结构的整个大小?

您在调用malloc使用的是错误的大小。

 struct Person* me = (struct Person*)malloc(sizeof(struct Person*)); ^^^^^^^^^^^^^^^ 

这是指针的大小,而不是对象的大小。 你需要使用:

 struct Person* me = (struct Person*)malloc(sizeof(struct Person)); 

为了避免这样的错误,请使用以下模式并且不要malloc的返回值(请参阅我是否转换了malloc的结果? ):

 struct Person* me = malloc(sizeof(*me)); 

malloc(sizeof(struct Person*)+4)工作原理巧合。 你的struct有一个指针和一个int 。 在你的平台上看起来sizeof(int)是4.因此, sizeof(struct Person*)+4恰好匹配struct Person的大小。

因为您希望分配足够的空间来容纳整个结构 ,而不仅仅是指向它的指针。

也就是说,使用sizeof(struct Person)而不是sizeof(struct Person*)

sizeof(struct Person*)+4 恰好在您的平台上足够大。