How does "free()" know the total allocated memory.

In C++,

I can often do this:

1
2
3
4
5
6
7
8
9
10
11
#include <stdlib.h>

int main() {
  int * buffer1, * buffer2, * buffer3;
  buffer1 = (int*) malloc (100*sizeof(int));
  buffer2 = (int*) calloc (100,sizeof(int));
  buffer3 = (int*) realloc (buffer2,500*sizeof(int));
  free (buffer1);
  free (buffer3);
  return 0;
}


Free appears to be an intelligent function. I'm clearly allocating an array. But I'm curious and surprised why my function "free" is able to recognize the exact amount of data needing to be freed.

Why am I not required to specify how much memory needs to be freed? How is free able to identify what is allocated and what isn't?

In other words, why does it know I had allocated a size of 100 * Sizeof(int)
Last edited on
It isn't that clever most of the time.

Some debug versions do checks on the block being returned. If you pass free an address that wasn't returned from an allocator (malloc/calloc/realloc), it's an error, but the program will just keep going until the bad heap state brings the system to an undignified and uncontrolable crash. You then have to work backwards trying to work out what went wrong.

Release versions don't do any checks at all for speed.

Remember, C was designed for controlling physical machinery directly. In some environments, timing is collected in nanoseconds, and engineers need to know where the time is going. Those environments are being developed in C++, the same holds true for C++.

The seemingly primitive nature of C++ is to support the direct control of machinery efficiently (code complexitity/cost to produce) and deterministically (runtime/space of code).
Last edited on
I found this:

https://gist.github.com/bellbind/507a426b0958eedb0fcf


Which is someone's own implementation, so I don't know how good it is. There are quite a number of static global variables, which points to the need of having used malloc first.

Last edited on
Topic archived. No new replies allowed.