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
Calling
free(ptr)
, afterptr
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
aftermalloc
. This new pointer should be used instead in thefree
function call. Is that right?
You have the following choice here:
Keep the original variable and use a copy to point to different locations of the malloc
ed data. Call free
using original variable.
Make a copy, use the original variable to point to different locations of the malloc
ed data. Call free
using copy.
Keep the original pointer. Use an index to access different locations of the malloc
ed 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
.
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
orrealloc
, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With