最近在调试Qt的程序,我在构造函数中为相关的对象申请了动态内存,也就是使用了new ,后面我在对应的析构函数中释放内存也就是使用delete的时候,发现它并没有按照我的想法执行相关的操作,在Qt中,有些内存是自动释放的,当为该对象指定父对象时,父对象的内存释放时,子对象占用的内存也一并释放了,当然我遇到的问题并非是这个,主要是两个问题一定要注意:
第一个就是:内存在被释放的时候,并不表示指针会消亡或者成为NULL指针,看下面这个情况,用C来说明:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *p=NULL;
p=(int *)malloc(sizeof(int));
if(p!=NULL)
{
printf("memory allocate success\r\n");
}
free(p);
printf("p:%p\r\n",p);
return 0;
}
运行结果:
root@ubuntu:/mnt/hgfs/WinShare/C# gcc testIf.c -o demo
root@ubuntu:/mnt/hgfs/WinShare/C# ls
demo list testIf.c
root@ubuntu:/mnt/hgfs/WinShare/C# ./demo
memory allocate success
p:0x8b81008
root@ubuntu:/mnt/hgfs/WinShare/C#
可以明显的看出来此时指针并非为NULL,为了安全,在释放内存时,也将指针设置为NULL,如下:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *p=NULL;
p=(int *)malloc(sizeof(int));
if(p!=NULL)
{
printf("memory allocate success\r\n");
}
free(p);
printf("p:%p\r\n",p);
/**************************/
p=NULL;
printf("p:%p\r\n",p);
/**************************/
return 0;
}
运行结果:
root@ubuntu:/mnt/hgfs/WinShare/C# gcc testIf.c -o demo
root@ubuntu:/mnt/hgfs/WinShare/C# ./demo
memory allocate success
p:0x9dec008
p:(nil)
第二个问题就是,指针消亡了,并不代表它所指向的内存会自动释放,用指针在函数中申请内存,申请的动态内存是在堆中申请的,需要自己管理申请释放,局部变量会随着函数消亡,自动释放,但是它所指向的内存并未释放:
void Func(void)
{
char *p = (char *) malloc(100);
}
这里用malloc申请的内存是不会自动释放的,malloc要与free配对,new要和delete配对。