Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should the pointer being passed to free() point to the start of the allocated space?

Say I used malloc to request a free space. The variable ptr points to the created memory space. In my code the value of ptr is changed to access different locations in my allocated space.

Calling free(ptr) , after ptr has been changed, would not be correct, no?. What I should do instead is to create a replica of ptr after malloc. This new pointer should be used instead in the free function call. Is that right?

Cheers

like image 287
user2005893 Avatar asked Mar 17 '23 17:03

user2005893


2 Answers

Calling free(ptr) , after ptr has been changed, would not be correct, no?

That is the correct understanding. It would not be correct.

What i should do instead is to create a replica of ptr after malloc. This new pointer should be used instead in the free function call. Is that right?

You have the following choice here:

  1. Keep the original variable and use a copy to point to different locations of the malloced data. Call free using original variable.

  2. Make a copy, use the original variable to point to different locations of the malloced data. Call free using copy.

  3. Keep the original pointer. Use an index to access different locations of the malloced data. Call free using original variable.

Regardless of the way you access different locations of the data returned by malloc, the value of the pointer that was returned by malloc must be used in the call to free.

like image 110
R Sahu Avatar answered Mar 19 '23 05:03

R Sahu


Yes, your understanding and suggested solution are correct. Moreover, according to the C11 standard,

7.22.3.3 The free function

...if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined

So trying to free somewhere in the middle of the memory you allocated causes undefined behavior and likely breaks your program.

like image 29
Patrick Collins Avatar answered Mar 19 '23 07:03

Patrick Collins