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 thatp2points to the same value asp1?- After freeing
p1why I can still printp2(Value of index 1 is different)? Am I causing any memory leak or pointer dangling? - Is this normal to be able to print
p2evenp1is freed?