尝试访问C中释放的内存时没有警告 [英] No warnings when trying to access freed memory in C
问题描述
我试图了解如何在C语言中管理内存.在下面的示例代码的注释中,我添加了对如何管理内存的理解.
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.
- 我想知道我是否正确
- 在代码的最后部分,我试图访问已释放的内存部分.我很惊讶为什么编译器没有通过任何警告
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?**
}
推荐答案
编译器不会检查非法的内存访问,您的程序将导致未定义的行为,甚至可能崩溃(分段错误).该行为是无法预测的,下次您运行程序时,它可能会崩溃.
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:
main
的签名应为int main(void)
或
int main(int argc, char *argv[])
.
此声明的评论有误.
node->pkeys = malloc(2*sizeof(int)); // creates a pointer pkeys in heap
您在分配内存并创建node
指向它时创建了指针pkeys
.该语句为2个int
的数组动态分配内存,并使pkeys
指向它.因此,当您执行node->pkeys = temp
时,会丢失动态分配的数组的句柄,并会导致内存泄漏.因此,在重新分配pkeys
之前,必须free
它指向的内存.
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 int
s 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
这篇关于尝试访问C中释放的内存时没有警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!