使用sizeof分配是否会为结构指针产生错误的大小? [英] Does allocating using sizeof yield wrong size for structure pointers?
问题描述
使用valgrind读取此消息:大小为4的无效读/写
Using valgrind to read this I get: Invalid write/read of size 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的干净日志
Using this got clean log with 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
不能获得结构的整个大小吗?
Why should I explicitly put sizeof(struct+intSize)
to avoid this error? sizeof
don't get the whole size of a struct?
推荐答案
您在调用malloc
时使用了错误的大小.
You are using the wrong size in the call to malloc
.
struct Person* me = (struct Person*)malloc(sizeof(struct Person*));
^^^^^^^^^^^^^^^
那是指针的大小,而不是对象的大小.您需要使用:
That is a size of a pointer, not the size of an object. You need to use:
struct Person* me = (struct Person*)malloc(sizeof(struct Person));
为避免此类错误,请使用以下模式,并且不要强制转换malloc
的返回值(请参见
To avoid errors like this, use the following pattern and don't cast the return value of malloc
(See Do I cast the result of malloc?):
struct Person* me = malloc(sizeof(*me));
malloc(sizeof(struct Person*)+4)
起作用是一个巧合.您的struct
有一个指针和一个int
.在您的平台上显示sizeof(int)
为4.因此,sizeof(struct Person*)+4
恰好与struct Person
的大小匹配.
It's a coincidence that malloc(sizeof(struct Person*)+4)
works. Your struct
has a pointer and an int
. It appears sizeof(int)
on your platform is 4. Hence, sizeof(struct Person*)+4
happen to match the size of struct Person
.
这篇关于使用sizeof分配是否会为结构指针产生错误的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!