Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer Assignment, malloc() and free() in C

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
  1. p2 = p1, does it mean that p2 points to the same value as p1?
  2. After freeing p1 why I can still print p2 (Value of index 1 is different)? Am I causing any memory leak or pointer dangling?
  3. Is this normal to be able to print p2 even p1 is freed?
like image 566
user3727663 Avatar asked May 09 '26 00:05

user3727663


1 Answers

p2 = p1, does it mean that p2 points to the same value as p1?

Yes, after the assignment both pointers point to the same region of memory.

After freeing p1 why I can still print p2 (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.

like image 133
Sergey Kalinichenko Avatar answered May 10 '26 14:05

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!