Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Freeing the allocated memory of a zero-length array in C

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?

like image 242
MaxGhost Avatar asked Feb 23 '23 06:02

MaxGhost


1 Answers

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.

like image 131
NPE Avatar answered Mar 08 '23 01:03

NPE