C 无返回值函数传入一级指针后造成的内存泄露问题

错误代码如下示:

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

void get_memory(char *p, int num)
{
  p = (char *)malloc(sizeof(char)*num);
}

int main(int argc,char *argv[])
{
  char *str = NULL;
  get_memory(str, 100);
  strcpy(str, "hello");
  printf("resut: %s\n", str);

  return 0;
}

 

linux下执行结果

$ ./tt
Segmentation fault

析:

调用函数 get_memory() 后,p将被系统释放,但由于malloc是在堆中分配的,只有当程序结束后才释放,这样将造成内存泄露。

linux下,由于函数调用后p的值变为了0x00,这样再执行strcpy时由于访问了无效地址而出现了段错误。

 

正确代码如(采用了二级指针方式)下:

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

void get_memory(char **p, int num)
{
  *p = (char *)malloc(sizeof(char)*num);
}

int main(int argc,char *argv[])
{
  char *str = NULL;
  get_memory(&str, 100);
  strcpy(str, "hello");
  printf("resut: %s\n", str);

  return 0;
}

执行结果如下:

$ ./tt
resut: hello
posted @ 2015-03-19 09:44  阿青1987  阅读(158)  评论(0编辑  收藏  举报