上下文
我正在尝试在 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
是一个可变长度数组 (VLA),这意味着它的大小是在运行时确定的。由于函数的局部变量驻留在堆栈上。然后,指针string
指向该数组,并返回该指针。并且由于返回的指针指向超出范围的本地堆栈变量,因此尝试使用该指针将调用 undefined behavior .
另请注意,VLA 是仅 C 语言的功能。
关于c++ - 动态创建的字符串分配在堆或堆栈上 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59315425/