1

I'm freeing a variable I allocated using malloc, but after I've freed it I try to access it and it still works fine.

I would expect a segmentation fault when accessing this memory but I dont get one.

Here is a simple example to show the problem:

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

int main() {
    int *arr = (int*)malloc(5*sizeof(int));
    arr[0] = 2;
    arr[4]=9;
    free(arr);
    printf("%d\n",arr[4]);
    return 0;
}

The output is 9.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Serofin
  • 57
  • 1
  • 5
  • 9
    Welcome to the wonderful world of *undefined behavior* – UnholySheep Aug 19 '20 at 08:43
  • 5
    Does this answer your question? [C - Accessing data AFTER memory has been free()ed?](https://stackoverflow.com/questions/42588482/c-accessing-data-after-memory-has-been-freeed) – UnholySheep Aug 19 '20 at 08:43
  • 1
    It's your responsibility as 4he programmer to not write bad or invalid code. Like attempting to use memory not belonging to your process. – Some programmer dude Aug 19 '20 at 08:50
  • 1
    Freeing the memory does not imply it is made inaccessible. There is no such (hardware) mechanism required by the C standard. The memory still exists, it only is not yours anymore and can be reused at any time. – Paul Ogilvie Aug 19 '20 at 09:01
  • 1
    Read [this](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794#6445794). It's not quite the same question but the explanation still applys very well to your question. Just replace _"How can it be? Isn't the memory of a local variable inaccessible outside its function?"_ with _"How can it be? Isn't the memory inaccessible once it has been freed with the `free` function?"_ – Jabberwocky Aug 19 '20 at 09:11

1 Answers1

1

I am sorry to say, the problem seems to be that you expect a segmentation fault.

The C language standard doesn't require a segmentation fault. Once you access a freed pointer anything can happen - including nothing.

Most likely, the memory allocator cached the memory for re-use instead of returning the memory to the system. This way, in case you would need to allocate memory again, the second allocation would be faster.

This means that, from a system's point of view, your program still "owns" that memory.

From an allocator's point of view, that memory is owned by the allocator and you shouldn't use it (the allocator might write its own data over there).

From your program's point of view you have a quite bug.

Myst
  • 18,516
  • 2
  • 45
  • 67