一、核心差异:两处 p 是完全独立变量
1. 一级指针传参场景(非法)
形参p是外部指针的值拷贝副本,和外部原指针分属两块独立栈变量。
执行p = malloc()仅修改副本保存的地址,外部指针完全不变,堆地址丢失,造成内存泄漏。
2. return 返回场景(合法)
函数内手动定义局部指针p,不存在外部传入副本。
return p把堆地址数值拷贝赋值给外部变量;函数销毁局部p不影响堆内存,地址可正常访问、释放。
二、正反对照代码(和正文示例统一)
示例 1 错误写法:一级指针入参 malloc
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void getmemory(char *p)
{
p = (char *)malloc(100); // 只修改临时副本p
strcpy(p, "hello world!");
}
int main()
{
char *str = NULL;
getmemory(str);
printf("%s\\n",str);
free(str);
return 0;
}
运行结果
示例 2 正确写法:内部局部指针 + return 返回堆地址
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* getmemory(void)
{
char *p = (char *)malloc(100); // 函数自有局部指针,非传入副本
strcpy(p, "hello world!");
return p; // 将堆地址拷贝给外部str
}
int main()
{
char *str = getmemory();
printf("%s\\n",str);
free(str);
return 0;
}
运行结果
三、极简总结
传参 p 只是外部指针副本,malloc 新地址无法同步到外部;
函数自建局部 p,依靠 return 直接导出有效堆地址,两段代码里的 p 完全互不干扰。
网硕互联帮助中心



![第5章,[Win32 章节] :边框绘制函数(二)-网硕互联帮助中心](https://www.wsisp.com/helps/wp-content/uploads/2026/08/20260811231700-6a7bad6c42588-220x150.png)

![P1014 [NOIP 1999 普及组] Cantor 表-网硕互联帮助中心](https://www.wsisp.com/helps/wp-content/uploads/2026/08/20260811104049-6a7afc31a3c58-220x150.png)

评论前必须登录!
注册