'When I free the dynamically allocated array in C the last value of array is not being freed, its not showing a garbage value [duplicate]

#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. **



Solution 1:[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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dbush