gpt4 book ai didi

c++ - 使用 alloca 时发生访问冲突

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:12:39 24 4
gpt4 key购买 nike

我的 stackAlloc 函数如下所示:

void* stackAlloc(size_t size) {
if (size > maxStackAllocation)
return malloc(size);
else
return _alloca(size);
}
void stackAllocFree(void *ptr, size_t size) {
if (size > maxStackAllocation) {
free(ptr);
}
}

如果我改变 stackAlloc 函数总是使用 malloc 而不是 alloca 一切正常。

我将函数更改为宏,现在它按预期工作:

#define maxStackAllocation 1024
#define stackAlloc(size) \
( \
(size > maxStackAllocation)? \
malloc(size): \
_alloca(size) \
)

#define stackAllocFree(ptr, size) \
( \
(size > maxStackAllocation)? \
free(ptr): \
void() \
)

最佳答案

假设您在 Windows 上运行,因为您的代码根据 MSDN documentation 调用 _alloca() :

_alloca allocates size bytes from the program stack. The allocated space is automatically freed when the calling function exits

请注意,调用函数退出时会释放内存 - 我假设这也意味着调用函数返回。

您的代码:

void* stackAlloc(size_t size) {
if (size > maxStackAllocation)
return malloc(size);
else
return _alloca(size);
}

返回,从而释放通过 _alloca() 获得的内存。

关于c++ - 使用 alloca 时发生访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37789732/

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