No warnings when trying to access freed memory in C [duplicate]

我只是一个虾纸丫 提交于 2019-12-02 17:28:45

问题


I'm trying to understand the how the memory is managed in C. In the sample code below, in the comments I have added my understanding on how the memory is managed.

  1. I would like to know if I'm correct
  2. In the final part of the code, I'm trying to access a part of memory which is already freed. I'm surprised why the compiler did not through any warnings
struct node
{
    int keys[2];
    int *pkeys;
};

int main()
{
    int temp[2] = {10,20}; // creates a temp array in stack
    struct node* node = malloc(sizeof(struct node)); //allocates a block of memory on heap pointed by node
    node->keys[0]=1;node->keys[1]=2;  // assigns values for keys present in heap
    node->pkeys = malloc(2*sizeof(int)); // creates a pointer pkeys in heap
    node->pkeys = temp; // the pointer pkeys in heap points to the temp array in stack
    free(node); // the block of memory on heap pointed by node is freed
    node->keys[0] = 9; //**Why does the compiler ignore that I'm accessing freed memory?**
}

回答1:


The compiler does not check for illegal memory access and your program will cause undefined behaviour or may even crash (segmentation fault). The behaviour is unpredictable and next time you run your program, it may crash.

Few things about your code:

The signature of main should either be int main(void) or
int main(int argc, char *argv[]).

The comment for this statement is wrong.

node->pkeys = malloc(2*sizeof(int)); // creates a pointer pkeys in heap

You created the pointer pkeys when you allocated memory and made node point to it. This statement is dynamically allocating memory for array of 2 ints and making pkeys point to it. So when you do node->pkeys = temp, you lose handle on the dynamically allocated array and will cause memory leak. So before reassigning pkeys, you must free the memory it points to.

free(node->pkeys);

// now reassign node->pkeys



回答2:


The compiler in C does not do that sort of checking. If gives enough rope to hang yourself.

It is up to you to do the checks. That is also true for bounds checking of arrays.

Also you need to note that malloc/free does not always have to beg/give to the OS. That means it may still be accessible by the process without seg fault.




回答3:


The space allocated to node is freed but node still points to the same location. So it is still accessible. But if you are unlucky (that is the OS reused the memory for its own purposes) you will get a segmentation fault.



来源:https://stackoverflow.com/questions/21950954/no-warnings-when-trying-to-access-freed-memory-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!