gpt4 book ai didi

c - alloca inside 复合语句

转载 作者:太空宇宙 更新时间:2023-11-04 01:57:54 26 4
gpt4 key购买 nike

是否可以在复合语句中使用 alloca?示例:

typedef struct
{
size_t len;
char* data;
} string_t;

#define str_to_cstr(str) \
({ \
char* v = alloca(str.len + 1); \
v[len] = 0; \
memcpy(v, str.data, str.len); \
})

// ... and somewhere in deep space
int main()
{
string_t s = {4, "test"};
printf("%s\n", str_to_cstr(s));
return 0;
}

根据我的经验,它运行良好,但我不确定它是否安全。顺便说一句,它是用 gcc 4.8.4 编译的

最佳答案

在您的示例中不安全:

 printf("%s\n", str_to_cstr(s));

来自 glibc documentation分配:

Do not use alloca inside the arguments of a function call—you will get unpredictable results, because the stack space for the alloca would appear on the stack in the middle of the space for the function arguments. An example of what to avoid is foo (x, alloca (4), y).

请注意,({}) 不是复合语句,而是 GNU C statement expression .

关于c - alloca inside 复合语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31360271/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com