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

本文探讨了C语言中使用malloc分配内存后如何避免内存泄露,并通过二级指针方式解决段错误问题,提供了从错误代码分析到正确代码实现的详细步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

错误代码如下示:

#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

转载于:https://www.cnblogs.com/aqing1987/p/4349553.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值