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: =========
    ======= Memory Map: ========

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); 



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.

Need Your Help

how can I take screenshot dynamically on android

android pdf screenshot jpeg

I am developing an android application on eclipse. I want to take screenshot of Emulator programmatically, as a jpg file to convert it to pdf when user clicks a button.

How Delete A Windows 7 dll File (In System32 Folder) By C# Language

c# file .net-4.0 delete-file permission-denied

Sometimes I need to delete or replace a dll file in system32 folder of windows 7.