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?
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.
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.
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.
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.
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);
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