日期:2014-05-16  浏览次数:20674 次

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