内存管理浅谈

《转》
 是临时的  
当跳出栈时,其指针对应的值被下次压栈替换掉  

可能每次出栈时,系统可能会对刚才压栈的内存初始化

#include<stdio.h>


char* GetString(){

char p[ ]="hello world";

return p; //编译警告

}

int main()

{

char* str=NULL;

str=GetString();

printf("%s",str);

}

此程序中,return返回的是指向栈内存的地址,程序编译警告,因为给该内存在函数结束时自动消亡。

 是指动态内存堆,,C++中由new和delete来分配和释放,C中由malloc和free来分配和释放,

它的生命周期是动态的,可以由程序员来创建和销毁。当然程序结束自动释放。

char *GetMemory(int num)
{
char *p = (char *)malloc(sizeof(char)*num);
return p;
}

void main(void)
{
char *str = NULL;
str = GetMemory(100);
strcpy(str, "hello world!");
cout << str << endl;
free(str);
str = NULL;
}

此程序中,return返回的是堆内存。函数结束时该内存还在,所以程序正常。

原文地址:https://www.cnblogs.com/marsggbo/p/6622967.html