否."string"
的内存是在程序执行期间分配的.
C程序的内存大致可以分为...
- 代码.
- 常数,如
"string"
和42
.
- 全局变量和静态变量.
- 堆栈(函数内为
char foo[50]
或int i
)
- 堆(
malloc
calloc
realloc
)
常量、全局变量和静态变量永远不会取消分配.
当函数返回时,堆栈被释放.这就是为什么不应该返回指向堆栈上分配的内存的指针.像int
和float
这样的简单值很好,因为值是复制的.
// Don't do this, foo will be deallocated on return.
char *function(){
char foo[10];
strcpy(foo, "string");
return foo;
}
// Don't do this either.
char *function(){
char foo = 'f';
return &foo;
}
// Nor this.
int *function(){
int i = 42;
return &i;
}
// But this is fine.
char function(){
char foo = 'f';
return foo;
}
堆仅在free
d时释放.
见Where will the Initialized data segment values are stored before run time?和Memory Layout of a C Program了解血淋淋的细节.