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

Find the age of a git branch

git git-branch git-merge

Let's say for example that I have

jQuery sortable elements depending on their attribute

javascript jquery html jquery-ui

I have couple of containers on page that are .sortable() therefore all elements inside that &lt;div&gt; can be moved around from one container to another, back and forth using connectWith option. B...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.