读书人

c malloc 内存泄露有关问题

发布时间: 2013-11-30 22:36:00 作者: rapoo

c malloc 内存泄露问题

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

typedef struct{
char a[20];
char b[100];
char c[150];
}test;

int main()
{

test *p2 = (test *)malloc(sizeof(test)*100);
if(p2 = NULL)
{
printf("malloc p2 error");
exit(1);
}
int a;
while(1)
{
test *p2 = (test *)malloc(sizeof(test)*100);
if(p2 = NULL)
{
printf("malloc p2 error");
exit(1);
}
sleep(0.5);

if(p2 != NULL)
{
free(p2);
p2 = NULL;
}


}

return 0;
}

为啥while中有个malloc 内存占用率极高呢? malloc 之后我还是free了啊!!!
[解决办法]
if(p2 = NULL) // 这是赋值,不是判空,要p2 == NULL

读书人网 >UNIXLINUX

热点推荐