0

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 ?

Edited by govindh2so4

4
Contributors
3
Replies
29
Views
4 Years
Discussion Span
Last Post by Schol-R-LEA
1

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;
}
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().

0

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.

Edited by Schol-R-LEA

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.