Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to a pointer to another pointer when the first one is freed? [duplicate]

I have made a simulation of a stack using malloc to create an array of MAX elements and assign it to a pointer. I then made a second pointer pointing to the first one, to be able to navigate back and forth, executing pushes and pops.

int * stack= (int *) malloc(MAX * sizeof(*stack));
int * stack_ptr = stack;

In the end, I delete the pointer containing the array, using

free (stack);

After I delete the array (stack), stack_ptr is pointing to an address with no contents, right?

Can this cause a memory leak or any kind of problem, even if the program terminates exactly after?

like image 898
Georgy90 Avatar asked Mar 11 '19 22:03

Georgy90


People also ask

What happens to a pointer when it is freed?

Calling free() on a null pointer results in no action being taken by free() . Setting message to NULL after it is freed eliminates the possibility that the message pointer can be used to free the same memory more than once.

What happens if you free a pointer twice in C?

C standard only says that calling free twice on a pointer returned by malloc and its family function invoke undefined behavior. There is no further explanation why it is so.

What happens when you assign one pointer to another?

Pointer assignment between two pointers makes them point to the same pointee. So the assignment y = x; makes y point to the same pointee as x . Pointer assignment does not touch the pointees. It just changes one pointer to have the same reference as another pointer.

What happens when one of two pointer variables that point to the same memory location is freed?

free() returns memory pointed to by a pointer back to the system. Thus if you have two pointers - once free is called the memory is returned to the system.


1 Answers

After I delete the array (stack), stack_ptr is pointing to an address with no contents, right?

After free(stack);, attempting to perform *stack_pt is undefined behavior (UB). The contents pointed to stack_pt may be good, bad or ugly or simply cause code to crash. It is UB to attempt to find out.

Can this cause a memory leak or any kind of problem, even if the program terminates exactly after?

Having a unchanged copy of the former valid pointer in stack_pt in itself in not a leak nor UB. Just don't use stack_pt.


Often after freeing, it is good practice to NULL the pointer(s).

int * stack= (int *) malloc(MAX * sizeof(*stack));
int * stack_ptr = stack;
...
free (stack);
stack = NULL;
stack_ptr = NULL;

Aside: Recommend to allocate to the size of the referenced object, not the type and forego the unneeded cast.

// int * stack= (int *) malloc(MAX * sizeof(*stack));
int *stack =  malloc(sizeof *stack * MAX);
like image 59
chux - Reinstate Monica Avatar answered Oct 18 '22 19:10

chux - Reinstate Monica