Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I still call free() on a variable that had a second malloc() call on it?

Tags:

c

memory

malloc

I was wondering if a malloc() call is tied to its initial variable that you assign malloc() to at all, when it comes to how the system frees the memory.

For example, can I do the following:

void * ptr1 = malloc(50);
void * ptr2 = ptr1;
ptr1 = malloc(25);
free(ptr2);

I was intending to free the memory that was initially assigned to ptr1, but later free it by another pointer.

like image 701
halfquarter Avatar asked Dec 11 '22 05:12

halfquarter


1 Answers

Let's walk through this step-by-step (UNDEF means that we don't know what a value is; valid means a pointer is safe to use):

void *ptr1, *ptr2;    /* ptr1=UNDEF (invalid), ptr2=UNDEF (invalid) */
ptr1 = malloc(50);    /* ptr1=0xAAA (valid),   ptr2=UNDEF (invalid) */
ptr2 = ptr1;          /* ptr1=0xAAA (valid),   ptr2=0xAAA (valid)   */
ptr1 = malloc(25);    /* ptr1=0xBBB (valid),   ptr2=0xAAA (valid)   */
free(ptr2);           /* ptr1=0xBBB (valid),   ptr2=UNDEF (invalid) */

free() doesn't know which if any variable the pointer it's passed is stored in; it isn't guaranteed to (but also isn't guaranteed not to) update or interact with the variables in any way. All that effectively changes from an application developer's perspective is whether it's safe to actually use that pointer, or any other references into the block of memory allocated during the malloc() call that returned it.

As mentioned by @M.M in comments, the C language specification is explicit that the value of a pointer to a deallocated object is undefined, and the compiler is permitted to modify it in any way; see Why does MISRA C state that a copy of pointers can cause a memory exception? for further discussion.

like image 113
Charles Duffy Avatar answered May 21 '23 10:05

Charles Duffy