0
#include <stdio.h>
#include <stdlib.h>

void printArr(int *ptr, int size)
{
    int i;
    for (i = 0; i < size; i++)
    {
        printf("%d\t", ptr[i]);
    }
    printf("\n");
}

int main(int argc, char const *argv[])
{
    int *ptr;
    ptr = (int *)malloc(4*sizeof(int));
    ptr[0] = 1;
    ptr[1] = 2;
    ptr[2] = 3;
    ptr[3] = 4;

    printArr(ptr, 4);
    free(ptr);
    printArr(ptr, 4);
    return 0;
}

Output :

1 2 3 4
-362921936 26425 2043 4

**Sorry for noobish question i just started learning about dynamic memory allocation. **

  • 1
    "*its not showing a garbage value*". That is an incorrect expectation. Calling `free` on memory does not guarantee that the memory is zeroed or set to any particular value. Accessing freed memory is Undefined Behaviour and any results from that are invalid. – kaylum May 18 '22 at 03:25

1 Answers1

1

The memory in question has in fact been freed. Reading from memory after it has been freed triggers undefined behavior.

"Garbage" values can be anything, including 0 or whatever might have been there before.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • but everytime its the same value as it was there at 3rd index – Mihir Patel May 18 '22 at 03:32
  • @MihirPatel That's one way undefined behavior can manifest itself. There's no guarantee that the value read will be anything in particular, including any value that might have been there before. – dbush May 18 '22 at 03:33