Releasing allocated memory of a zero-length array in C

Today I learned a new trick, consisting of completing a structure with an array of zero length to allow the array to be dynamically evaluated as needed. This is very convenient and helps to save a good amount of memory when I want to determine the amount of space that my structure will consume at runtime, and not compile time.

Using them works fine; then I remembered that I needed to free the allocated memory, so I just threw away the free (structure); there, but to my horror, which threw me an error:

*** glibc detected *** ./program: free(): invalid next size (fast): <address> ======= Backtrace: ========= <omitted> ======= Memory Map: ======== <omitted> 

Here is 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 an error on free (ptr);

Any ideas?

+4
source share
4 answers

Your malloc() / free() code is fine. To check, comment on everything between malloc() and free() and see if the problem goes away (I'm sure it does).

You almost certainly write 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 initialized correctly.

+6
source

Remove doStuff () just for free (ptr) and try again. Do you have the same error?

+1
source

Maybe your code changes the ptr value somewhere.

Using:

 struct Stuff * const ptr = ... 

Instead:

 struct Stuff * ptr = ... 

To detect such problems during compilation.

+1
source

Probably everything you do in doStuff() uses more than 30 extra bytes allocated behind the structure header. Make sure that you correctly calculate the amount of space you need.

0
source

Source: https://habr.com/ru/post/1384090/


All Articles