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?
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->sizeto determine the size ofptr->data, make sureptr->sizeis initialized correctly.