释放 C 中零长度数组的分配内存
我今天学到了一个新技巧,包括以零长度数组结束结构,以允许该数组根据需要动态调整大小。当我想决定我的结构在运行时而不是编译时占用的空间量时,这非常方便,并且有助于节省大量内存。
使用它们效果很好;然后我记得我需要释放分配的内存,所以我只是扔掉了一个 free(struct);在那里,但令我沮丧的是,这给我带来了一个错误:
*** glibc detected *** ./program: free(): invalid next size (fast): <address>
======= Backtrace: =========
<omitted>
======= Memory Map: ========
<omitted>
这是一个格式不正确的代码的简单示例:
struct Stuff {
int size; // defines the amount of bytes the entire struct will take up
char data[0];
}
...
// This gives me an int and a char[30].
struct Stuff *ptr = (struct Stuff *) malloc(sizeof(struct Stuff) + 30);
...
doStuff();
...
free(ptr);
我在 free(ptr); 处收到错误
有什么想法吗?
I learned a new trick today, consisting of ending a struct with a zero-length array to allow that array to be dynamically sized as I need it. This is extremely handy and helps save a good amount of memory when I want to decide the amount of space my struct will eat up at run-time instead of compile time.
Using them works perfectly; then I remembered I need to free my allocated memory, so I just threw down a free(struct); in there, but to my dismay, that threw me an error:
*** glibc detected *** ./program: free(): invalid next size (fast): <address>
======= Backtrace: =========
<omitted>
======= Memory Map: ========
<omitted>
Here's a simple example in poorly formatted code:
struct Stuff {
int size; // defines the amount of bytes the entire struct will take up
char data[0];
}
...
// This gives me an int and a char[30].
struct Stuff *ptr = (struct Stuff *) malloc(sizeof(struct Stuff) + 30);
...
doStuff();
...
free(ptr);
And I get the error at free(ptr);
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的
malloc()
/free()
代码很好。要进行验证,请注释掉malloc()
和free()
之间的所有内容,然后查看问题是否消失(我打赌它会消失)。几乎可以肯定,您的写入超出了已分配内存的末尾(可能在
doStuff()
中)。例如,如果doStuff()
使用ptr->size
来确定ptr->data
的大小,请确保ptr->size
已正确初始化。Your
malloc()
/free()
code is fine. To verify, comment out everything between themalloc()
and thefree()
, and see if the problem goes away (I bet it does).You almost certainly write past the end of the allocated memory somewhere (possibly in
doStuff()
). For example, ifdoStuff()
usesptr->size
to determine the size ofptr->data
, make sureptr->size
is initialized correctly.删除 doStuff() 以保留 free(ptr) 并重试。你有同样的错误吗?
Remove doStuff() for just leaving free(ptr) and retry. Do you have the same error ?
也许您的代码在某处更改了
ptr
的值。使用:
代替:
在编译时检测此类问题。
Maybe your code changes value of
ptr
somewhere.Use:
Instead of:
To detect this kind of problems at compile time.
可能您在
doStuff()
中所做的任何操作都使用了超过结构体标头之外分配的 30 个额外字节。确保您正确计算了所需的空间量。Probably whatever you are doing in
doStuff()
is using more than the 30 extra bytes you've allocated beyond the struct header. Make sure you are correctly calculating the amount of space you need.