c++ - 在堆或堆栈上分配的动态创建的字符串 - 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 字符串是在堆还是栈上分配的?
据我所知:
calloc
使用,malloc
&realloc
C 标准函数或new
&new[]
C++ 关键字进行堆分配。大多数其他情况下的堆栈分配。
解决方案
该数组buffer
是一个可变长度数组(VLA),这意味着它的大小是在运行时确定的。由于函数的局部变量驻留在堆栈上。然后指针string
指向该数组,并返回该指针。并且由于返回的指针指向超出范围的本地堆栈变量,因此尝试使用该指针将调用未定义的行为。
另外,请注意 VLA 是 C 唯一的功能。
推荐阅读
- c - 如何修复函数“_start”中的错误:(.text+0x20):未定义对“main”的引用
- java - 带有内容 Uri 的 Android VIEW 意图
- html - How to build a responsive CSS grid with square items to display images with multiple aspect ratios
- php - 从数据库生成 Doctrine 实体但不覆盖当前实体中的自定义代码
- sql - SQL插入多个选择
- c# - 在 Mono/Linux 中使用 FFmpeg.Autogen 4.1.0.2 时未找到 Kernel32
- python - NodeVisitor class for PEG parser in Python
- angular - Selecting a specific TemplateRef from Angular component test?
- flume - 如何解决 Flume Syslog 设置错误 - “事件大小大于指定的事件大小:2500。考虑增加最大事件大小”
- opengl - Load float array with 3D texture?