mingshaox 发表于 2022-3-6 01:21:16

我在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:26:33

本帖最后由 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();
}

mingshaox 发表于 2022-3-6 01:30:29

此刻
return(p);分函数结束后内容却已更改

wp231957 发表于 2022-3-6 07:22:47

mingshaox 发表于 2022-3-6 01:30
此刻
return(p);分函数结束后内容却已更改

不知道你要问①楼的代码还是要问②楼的代码

jhq999 发表于 2022-3-6 07:27:48

也不是静态数组,谁告诉你函数结束自动释放?最多程序结束后系统回收

2736946915 发表于 2022-3-6 09:05:33

函数释放掉的是&p这个地址,不是*p
函数的返回值还保存在eax寄存器中,通过“=”赋值到了str中,

2736946915 发表于 2022-3-6 09:16:14

函数内有值,函数外为0

mingshaox 发表于 2022-3-6 13:58:53

#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]
查看完整版本: 我在char*G..函数结束后*p就会释放掉,为啥malloc(100)仍然有效