Search code examples
cmallocdynamic-memory-allocation

Memory not freed after calling free - C


I have a question regarding the following matter. So I have this small function that creates an array of 10 integers and returns the pointer to it.

int* create_int_array()
{
    int* arr = (int*)malloc(sizeof(int) * 10);
        
    for(int i = 0; i < 10;i++)
    {
        arr[i] = i+1;
    }

    return arr;
}

I print its values and free it then I try printing it again but the values are still correct. It didn't give me some random numbers it kept the original ones.

int main(int argc, char* argv[])
{
    int* ptr_to_array = create_int_array();
    for(int i = 0;i < 10;i++){printf("%d ", ptr_to_array[i]);}
    free(ptr_to_array);
    printf("\n");
   
    for(int i = 0;i < 10;i++){printf("%d ", ptr_to_array[i]);}
    
    return 0;
}

The output looks like this

1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10

I thought it should look something like this

1 2 3 4 5 6 7 8 9 10
<   garbage values   >

Solution

  • Accessing data after it's been free'ed is undefined behavior. There would a cost to clearing memory so it's not typically done automatically in production builds.