free(...) 上的堆损坏

发布于 2025-01-08 09:11:45 字数 456 浏览 3 评论 0原文

我有这个 enum 类型:

enum Cell { ALIVE='X', DEAD='O' };

并且我用它分配了一个数组:

h_board = (Cell*) malloc(width*height*sizeof(char));

我认为我没有做错,因为 Cell 值是字符(我想保留char 大小的数据,但我关心可读性,这就是我使用 enum 的原因。)

free(h_board); 时,会抛出异常。在调试模式下,我可以看到堆损坏警告。我想我释放的内存比分配的内存多,但我不明白为什么。我还尝试了 free((char*)h_board); 尝试强制执行 char 大小释放,但问题仍然存在。

我该如何解决这个问题?

I have this enum type:

enum Cell { ALIVE='X', DEAD='O' };

And I allocate an array with it:

h_board = (Cell*) malloc(width*height*sizeof(char));

I assume I'm not doing this wrong since Cell values are chars (I'd like to stay with char sized data but I care for readability, that's why I used the enum.)

Upon free(h_board); an exception is thrown. In debugging mode I can see a heap corruption warning. I guess I'm freeing more memory than I'm allocating, but I can't see why. I also tried free((char*)h_board); trying to enforce char size deallocation, but the problem persists.

How can I fix this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

り繁华旳梦境 2025-01-15 09:11:45

首先,Cell 是它自己的数据类型(不一定映射到 char),因此请使用 malloc(另外,我们不会强制转换 malloc in C):

Cell *h_board = malloc(width * height * sizeof(Cell));

其次,我们需要完整的代码才能准确地帮助您。这应该运行没有任何错误,也许你可以从这里构建:

#include <stdlib.h>

int main(int argc, char **argv) {
    Cell *h_board;

    h_board = malloc(20 * 30 * sizeof(*h_board));
    free(h_board);

    return 0;
}

First of all, Cell is it's own datatype (which doesn't necessarily map to char), so use malloc with that (plus, we don't cast malloc in C):

Cell *h_board = malloc(width * height * sizeof(Cell));

Second, we need the full code to be able to help you accurately. This should run without any errors, perhaps you can build from here:

#include <stdlib.h>

int main(int argc, char **argv) {
    Cell *h_board;

    h_board = malloc(20 * 30 * sizeof(*h_board));
    free(h_board);

    return 0;
}
眼藏柔 2025-01-15 09:11:45

它应该是 sizeof(Cell)。对枚举的大小做出任何假设都可能是危险的。
仅供您参考: C 中枚举的大小是多少?

It should be sizeof(Cell). Making any assumptions about the size of the enum can be dangerous.
Just for your reference : What is the size of an enum in C?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文