动态创建的分配在堆或堆栈上的字符串-C

问题描述 投票:0回答:3

上下文

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

据我所知:

  • 堆分配与callocmallocrealloc C标准函数或newnew[] C ++关键字一起发生。

  • 在大多数其他情况下,堆栈分配。

c++ c memory allocation
3个回答
1
投票

数组buffer可变长度数组


0
投票

[@ PaulMcKenzie指出,您对get_empty_c_string()的实现将无法编译:本质上,数组作为函数的临时/实例变量需要在编译之前为其定义静态大小。这是因为在调用函数时该内存量被压入堆栈中


0
投票

[标准C ++中没有办法获得自动存储持续时间的运行时大小的内存(通常映射到堆栈内存)。

© www.soinside.com 2019 - 2024. All rights reserved.