我正在尝试在C ++中获取C字符串而不在堆上分配内存,并在测试中遇到了这一点:
#include <stddef.h>
#include <stdlib.h>
char* get_empty_c_string(size_t length) {
char buffer[length];
char *string = buffer;
for (size_t i = 0; i ^ length; i++) *(string + i) = '\0';
return string;
}
int main(void) {
char *string = get_empty_c_string(20u); // Allocated on heap?
// or stack?
return 0;
}
返回的C字符串是分配在堆还是堆栈上?
据我所知:
堆分配与calloc
,malloc
和realloc
C标准函数或new
和new[]
C ++关键字一起发生。
在大多数其他情况下,堆栈分配。
数组buffer
是可变长度数组
[@ PaulMcKenzie指出,您对get_empty_c_string()
的实现将无法编译:本质上,数组作为函数的临时/实例变量需要在编译之前为其定义静态大小。这是因为在调用函数时该内存量被压入堆栈中
[标准C ++中没有办法获得自动存储持续时间的运行时大小的内存(通常映射到堆栈内存)。