gpt4 book ai didi

c - malloc 覆盖结构元素

转载 作者:行者123 更新时间:2023-12-02 06:26:50 26 4
gpt4 key购买 nike

在将 0 分配给 count 之前调用 malloc 按预期工作。但是,如果我在将 0 分配给 count 之后调用 malloc,那么它将覆盖 count 的值。每次运行时,我都会为 count 打印一个随机数。

有人可以解释为什么 count 被覆盖了吗?

#include <stdio.h>
#include <stdlib.h>

typedef struct list list;

struct list {
size_t element_size;
size_t capacity;
size_t count;
void* data;
};

list* create_list(size_t element_size) {
list* list = malloc(sizeof(list));

list->element_size = element_size;
list->capacity = 8;
list->data = malloc(8 * element_size);
list->count = 0;

// If malloc is called here instead then count is overwritten
// list->data = malloc(8 * element_size);

printf("count: %zu\n", list->count);

return list;
}

int main(int argc, char** argv) {
list* l = create_list(sizeof(int));
}

最佳答案

啊,我觉得问题出在这里:

list* list = malloc(sizeof(list));

sizeof(list) 给出指针的大小,因为此时 list 是一个指针,不再是结构类型。因此,您分配的内存太少,并在通过写入未分配的内存来初始化结构数据时遇到未定义的行为。

通过更改变量或类型名称来修复...或使用 sizeof(*list) 获得正确的大小。或者,如果您需要我的意见/偏好,请不要将 typedef 与结构一起使用。或者其中的几个,所以这里你可能有 struct list *lst = malloc(sizeof(*lst));


尽管使用未定义行为通常效率不高,但我们可以对可能发生的情况进行有根据的猜测:如果在写入超出分配的 0 后调用 malloc,则 malloc 创建一个新的分配并用它自己的分配数据覆盖 0,然后您在输出中获得该值。如果你以其他方式进行,写入 0 将覆盖分配数据。从长远来看,两者都是非常致命的,因此您可以认为自己很幸运,您注意到了奇怪的输出并及早发现了 UB,而不是后来出现神秘的崩溃。

关于c - malloc 覆盖结构元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57741472/

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