C语言:CRT detected that the application wrote to memory after end of heap buffer

最近遇到个问题:释放一个数组头指针时出错。

大致代码如下:

Value_t *allVariableValues;
#ifdef _MSC_VER
    allVariableValues = (Value_t *)_malloca(moduleVariablesCount + chipVariablesCount + 3);
#endif
for(;;)
{
    allVariableValues[2 + moduleVariablesCount + counter].i = ###;
}
#ifdef _MSC_VER
    _freea(allVariableValues);
#endif

程序在 _freea(allVariableValues); 报错。

绕了些弯后,发现是_malloca时犯了错。 _malloca是按字节数申请内存的。而这里 Value_t类型占了8个字节。也就是说这里只申请了10个字节。但for循环里用了80个字节。怪不得会报错。

修改后的代码:

#ifdef _MSC_VER
    allVariableValues = (Value_t *)_malloca(sizeof(Value_t) * (moduleVariablesCount + chipVariablesCount + 3));
#endif

感谢 CRT detected that the application wrote to memory after end of heap buffer-CSDN博客

lcfeng1982 ​​​​​​​ ​​​​​​​ 

你可能感兴趣的:(语言学习,c语言,缓存,开发语言)