I'm very new in C programming and I was playing around with malloc(), free() and Pointer Assignment in order to get a better grasp of it.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
void
array_fill(int * const arr, size_t n)
{
size_t i;
for (i = 0; i < n; i++)
arr[i] = i;
}
void
array_print(const int * const arr, size_t n)
{
size_t i;
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
int
main(int argc, char ** argv)
{
int * p1, * p2;
p1 = (int *) malloc(SIZE * sizeof(int));
p2 = p1;
array_fill(p1, SIZE);
array_print(p1, SIZE);
array_print(p2, SIZE);
printf("\nFREE(p1)\n");
free(p1);
array_print(p2, SIZE);
return (0);
}
Compiling it with gcc test.c -o test and running it with ./test:
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
FREE(p1)
0 0 2 3 4 5 6 7 8 9
p2 = p1, does it mean that p2 points to the same value as p1?p1 why I can still print p2 (Value of index 1 is different)? Am I causing any memory leak or pointer dangling?p2 even p1 is freed?
p2 = p1, does it mean thatp2points to the same value asp1?
Yes, after the assignment both pointers point to the same region of memory.
After freeing
p1why I can still printp2(Value of index 1 is different)? Am I causing any memory leak or pointer dangling?
Yes, once you free p1, the p2 pointer becomes dangling. Accessing anything through it is undefined behavior.
Is this normal to be able to print p2 even p1 is freed?
No, it is undefined behavior.
Don't let the fact that you see numbers that look like ones that you have previously confuse you: any resemblance with the numbers that were there before you called free is a complete coincidence. Unfortunately, coincidences like that make problems with dangling pointers extremely hard to find. To aid with this problem, memory profiler programs take over the free-d region, and deliberately write some garbage values into it. This makes detection faster, but it is not bulletproof.
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