当前位置: 代码迷 >> 综合 >> 堆与栈内存
  详细解决方案

堆与栈内存

热度:81   发布时间:2024-01-15 22:33:24.0
堆内存
栈内存
一、
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;
}
二、
char *GetMemory()
{
char p = "hello world";
return p;
}

void main(void)
{
char *str = NULL;
str = GetMemory();
cout << str << endl;
return ;
}
哪个是错的呢,二是错的(例子中返回的指针P是指向栈内存) 一返回的指针P是指向堆内存(
这里的堆是指动态内存堆,C++中由new和delete来分配和释放,C中由malloc和free来分)
  相关解决方案