最近在接触c语言项目,使用VLD查看内存泄漏,就一直在纠结结构体中如果定义了指针变量,在外面使用malloc为其分配了空间,那仅仅释放结构体指针可以吗?会存在内存泄漏吗?因此做了个小实验,前面话比较绕,描述可能有问题,那么直接上代码:
首先定义结构体:
#include<vld.h>
#include<stdio.h>
#include<stdlib.h>
struct Test
{
unsigned char* ucTest;
int a;
};
结构体中包含了一个uchar指针(后面为其分配内存空间,问题的核心也在这里:需不需要单独释放后面为其分配的内存呢?)和int变量。
首先不单独释放,测试代码如下:
void test()
{
Test* test = NULL;
test = (Test*)malloc(sizeof(Test) * 4);
for (int i = 0; i < 4; i++)
{
test[i].ucTest = (unsigned char*)malloc(10);
test[i].a = i;
}
//for (int i = 0; i < 4; i++) //单独释放结构体中数组的内存。
//{
// free(test[i].ucTest);
// test[i].ucTest = NULL;
//}
free(test);//释放结构体数组
test = NULL;
}
运行程序,发现VLD提示内存泄漏,结果如下所示:
Visual Leak Detector detected 4 memory leaks (184 bytes).
Largest number used: 252 bytes.
Total allocations: 252 bytes.
Visual Leak Detector is now exiting.
The program '[4820] test.exe' has exited with code 0 (0x0).
查找内存泄漏的地方,定位到
test[i].ucTest = (unsigned char*)malloc(10);
从而猜想可能需要单独释放内存,因而取消掉单独释放内存的注释,继续运行程序:
No memory leaks detected.
Visual Leak Detector is now exiting.
提示无内存泄漏。说明还是需要单独释放内存的。
PS: C语言这个语言真的细节很多,之前写代码都是实现功能就行,对于细节把握不足,后面这个方面还是需要改进。自己算是C语言小白,如果有问题希望大家能够指出。