Search code examples
cpointersmallocpointer-to-pointer

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


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?


Solution

  • 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);