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 the malloc()
and the free()
, 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, if doStuff()
uses ptr->size
to determine the size of ptr->data
, make sure ptr->size
is initialized correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With