gpt4 book ai didi

c - 使用 sizeof 进行分配是否会为结构指针产生错误的大小?

转载 作者:太空宇宙 更新时间:2023-11-04 05:36:09 25 4
gpt4 key购买 nike

使用 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 的返回值(参见 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.

关于c - 使用 sizeof 进行分配是否会为结构指针产生错误的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35144511/

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