Josh Weinstein
Josh Weinstein

Reputation: 2968

Does free deallocate all the memory of a larger struct pointer from a smaller one?

So, I am trying to implement a polymorphic system in C, similar to that of PyObject and the Python object system. However, I am having trouble understanding how a struct cast from a base struct can be freed. I have implemented the following base and advanced struct types:

#include "stdio.h"
#include "stdlib.h"

//testing for garbage collection

//base handler to ensure polymorphism
#define BASE char g;

struct temp {
  BASE
  short w;
};

struct femp {
  BASE
  short w;
  long d;
};


int main(void) {
  struct femp* first = malloc(sizeof(struct femp));
  first->d = 3444;
  struct temp* second = (struct temp*)first;
  free(second); // does this deallocate all the memory of first?
  free(first);
  return 0;
}

note: The above program exits with nonzero status if second is freed, but not first.

result:

7fb829d02000-7fb829d04000 rw-p 00000000 00:00 0 
7fb829d0c000-7fb829d10000 rw-p 00000000 00:00 0 
7fb829d10000-7fb829d11000 r--p 00023000 00:136 38                        /usr/lib/x86_64-linux-gnu/ld-2.24.so
7fb829d11000-7fb829d12000 rw-p 00024000 00:136 38                        /usr/lib/x86_64-linux-gnu/ld-2.24.so
7fb829d12000-7fb829d13000 rw-p 00000000 00:00 0 
7fffac407000-7fffac428000 rw-p 00000000 00:00 0                          [stack]
7fffac499000-7fffac49b000 r--p 00000000 00:00 0                          [vvar]
7fffac49b000-7fffac49d000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
exited with non-zero status

My question is, does calling free() on a pointer to a smaller sized struct, which is casted from an original malloc'd larger size struct, still free all of the memory? like in my code, is there any difference from freeing first or second? Should you always cast back to the original type before freeing?

Upvotes: 0

Views: 60

Answers (1)

Lee Daniel Crocker
Lee Daniel Crocker

Reputation: 13171

malloc() / free() know nothing at all about your structures. malloc() takes an integer argument and allocates that many bytes, giving you a memory address. free() takes that address, and frees whatever was allocated. What you do with it in the meantime is up to you.

If you need some memory that might possibly hold one of two things, it's up to you to make sure it's big enough. If you allocate a 5-gallon bucket and only use it to carry 3 gallons, that's fine. If you try to carry 7 gallons, you'll get your feet wet. C will not interfere with you doing either.

Upvotes: 3

Related Questions