我在面试中被问过
结构中的内存泄漏是什么?我们怎样才能纠正这个问题呢?
任何人都可以帮助我理解结构中的记忆泄漏吗?
答案 0 :(得分:5)
我想明显的答案是结构中的泄漏是指向指向已分配内存的指针驻留在结构中,并且结构在其成员指向的内存被释放之前超出范围。在释放(或放弃范围)结构之前,通过释放从结构内部指向的任何内存来纠正它。
很确定这就是问题所在......:)
答案 1 :(得分:1)
要记住的重点是:
始终分配动态内存以及明确解除分配。
任何时候使用malloc
为指针分配内存并且不在同一指针上显式调用free
/将同一地址传递给free
它会导致内存泄漏
在结构的情况下,只要你有一个使用malloc
分配动态内存的指针成员,那么它应该通过调用free
显式地free
d,而不能这样做会导致内存泄漏。
<强> An Code Example: 强>
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
struct MyStruct
{
char *str;
int i;
};
int main()
{
struct MyStruct *ptr = (struct MyStruct *)malloc(sizeof(*ptr));
ptr->i = 10;
/*str is allocated dynamic memory*/
ptr->str = malloc(10);
strncpy(ptr->str,"Hello",6);
printf("[%d]",ptr->i);
printf("[%s]",ptr->str);
/*Frees memory allocated to structure*/
/*But Oops you didn't free memory allocated to str*/
/*Results in memory leak*/
//free(ptr);
/*Correct order of deallocation*/
/*free member memory*/
free(ptr->str);
/*free structure memory*/
free(ptr);
return 0;
}
答案 2 :(得分:1)
请查看Dynamic memory allocation in C
动态内存分配/释放期间发生的常见错误如下[解释here]
动态内存分配的不当使用通常会成为错误的来源。
最常见的错误如下:
free
无法释放内存会导致内存堆积,这是不可重复使用的内存,程序不再使用该内存。这会浪费内存资源,并在这些资源耗尽时导致分配失败。malloc
进行分配,使用存储数据,使用free
进行重新分配。无法遵守此模式,例如在拨打免费电话或拨打malloc
之前调用内存时,调用free
两次等等,通常会导致程序崩溃。上述内容适用于structures
以及C
的其他结构。
希望这有帮助!