free(...) 上的堆损坏
我有这个 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,
Cell
是它自己的数据类型(不一定映射到char
),因此请使用 malloc(另外,我们不会强制转换malloc
in C):其次,我们需要完整的代码才能准确地帮助您。这应该运行没有任何错误,也许你可以从这里构建:
First of all,
Cell
is it's own datatype (which doesn't necessarily map tochar
), so use malloc with that (plus, we don't castmalloc
in C):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:
它应该是 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?