我在char*G..函数结束后*p就会释放掉,为啥malloc(100)仍然有效
#include"stdio.h"#include"stdlib.h"
char* GetMemory(char *p)
{
p = malloc(100);
return p;
}
void Text()
{
char *str = NULL;
str = GetMemory(str);
strcpy(str, "hello,world");
printf(str);
free(str);
str = NULL;
}
void main()
{
Text();
}
本帖最后由 mingshaox 于 2022-3-6 01:29 编辑
#include"stdio.h"
#include"stdlib.h"
char* getMemory()
{
char p[] = "hello,world!"
return p;
}
void Text()
{
char *str = NULL;
str = GetMemory();
printf(str);
}
void main()
{
Text();
} 此刻
return(p);分函数结束后内容却已更改 mingshaox 发表于 2022-3-6 01:30
此刻
return(p);分函数结束后内容却已更改
不知道你要问①楼的代码还是要问②楼的代码 也不是静态数组,谁告诉你函数结束自动释放?最多程序结束后系统回收 函数释放掉的是&p这个地址,不是*p
函数的返回值还保存在eax寄存器中,通过“=”赋值到了str中, 函数内有值,函数外为0 #include"stdio.h"
#include"stdlib.h"
char* GetMemory()
{
char p[] = "hello,world!";
return p;
}
void Text()
{
char *str = NULL;
str = GetMemory();
printf(str);
}
void main()
{
Text();
}
岨.Press any key to continue
页:
[1]