【发布时间】:2014-10-13 12:21:38
【问题描述】:
以下程序的可能行为是什么?
我尝试在堆栈上分配和使用内存, 并打印p指向的内存块,输出为'\0'字符。
我知道在函数返回时它在技术上不可用。
但是,为什么程序不崩溃,或者打印一些随机垃圾?
#include <cstring>
#include <cstdio>
#include <cstdlib> //malloc
char* getStackMemory(){
char mem[10];
char* p = mem;
return p;
}
int main(){
char* p = getStackMemory();
strcpy(p, "Hello!");
printf("%s\n", p);
for(int i = 0; i<10; i++){
printf("%c\n", p[i]);
}
return 0;
}
【问题讨论】:
-
这些是非常基本的概念,涵盖在任何 2 分钟搜索将挖掘出的无数教程的第一章中。