Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C free() routine and incremented array pointers

Will the free() routine work if I dynamically allocate an array and then pass, not the initial pointer, but a pointer to the middle of the array? Example:

int* array = malloc(10 * sizeof *array);
if(array) {

  array += 5; // adjusting the indicies

  free(array);
}

Or do I need to set the pointer back to the start of the array before calling free()?

like image 513
Dan Avatar asked Mar 24 '11 03:03

Dan


2 Answers

Absolutely not. The value passed to free() must be exactly the same value returned by malloc(). In fact, to ensure this is the case, I would recommend you use a copy of the pointer if you need a pointer you can increment or otherwise modify.

like image 152
Jonathan Wood Avatar answered Sep 30 '22 01:09

Jonathan Wood


No

(And "Yes", you do need to "set it back".)

The API requires that you only pass to free() exactly what you got from malloc()1.


1. Or a null pointer.

like image 35
DigitalRoss Avatar answered Sep 30 '22 00:09

DigitalRoss