首页 > 解决方案 > 在堆或堆栈上分配的动态创建的字符串 - C

问题描述

语境

我正在尝试在 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 字符串是在堆还是栈上分配的?

据我所知:

标签: c++cmemoryallocation

解决方案


该数组buffer是一个可变长度数组(VLA),这意味着它的大小是在运行时确定的。由于函数的局部变量驻留在堆栈上。然后指针string指向该数组,并返回该指针。并且由于返回的指针指向超出范围的本地堆栈变量,因此尝试使用该指针将调用未定义的行为

另外,请注意 VLA 是 C 唯一的功能。


推荐阅读