I have a program like this:

int main ()
{
  int * buffer1;
  buffer1 = (int*) malloc (100*sizeof(int));
  buffer1 = buffer1 + 5;

  free (buffer1);
  return 0;
}

So my doubt: How much int-sized memory will this free-function free. 100 or 95 ?

It wont do either it will cause undefined behaviour.

You must call free on the actually pointer value returned by malloc. If for some reason you need to increment the pointer you should use a copy so you can still free the original pointer.

int main ()
{
  int * buffer1;
  int * buffer2;
  buffer1 = malloc (100*sizeof(int));
  buffer2 = buffer1 + 5;

  free (buffer1);
  return 0;
}

Zero. The pointer given to free() is not in its list of allocated blocks. Usually, free does not check for blocks that are inside the block that it knows is allocated; the pointer must match exactly what was given by malloc().

Both answers are accurate, but Banfa's answer is the correct one. Nutster's answer is true in the majority of implementations, but not all, and according to the standard the behavior is implementation dependent. You cannot count on any specific result without knowing the implementation in question.

As one famous quip on the subject went: 'undefined behavior' means that the program can, for example, cause demons to fly out of your nose if that happens to be the way it was implemented.

Note that this is not the same as random behavior; the implementation is generally still going to be deterministic, with a given implementation consistently giving the same results. You simply cannot anticipate the behavior from the standard. A consistent behavior on a given compiler, or even several compilers with similar implementations, does not change the fact that it is undefined by the standard.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.