![](/img/trans.png)
[英]C6386 - Buffer overrun while writing to 'buffer' when using fread() function
[英]c6386 buffer overrun while writing
- 函數名稱:expandStack
- 輸入:指向 Stack 類型 (Stack*) 的指針
- 輸出:無
- 函數操作:函數擴展一個堆棧
void expandStack(Stack* stack){
//Check the stack and the array are allocated
if (stack == NULL ||stack->content == NULL)
{
return;
}
//Allocating a new sized array (*2 from the previous)
Element* expandedStack = (Element*)malloc(2 * (stack->size) * sizeof(Element));
//Case malloc failed
if (expandedStack == NULL)
{
printf("Error! Malloc has failed in file 'stack.c', 'expandStack' function\n");
return;
}
//Updating size field
stack->size *= 2;
//Copy values from the previous array to the new array allocated
for (int i = 0; i <= stack->topIndex; i++)
{
expandedStack[i].c = stack->content[i].c;
}
//Free old array
free(stack->content);
//Point to the new array in the heap
stack->content = expandedStack;
}
在這一行中: expandStack[i].c = stack->content[i].c; 我收到一條“綠色警告”,說:“寫入 'expandedStack' 時 c6386 緩沖區溢出:可寫大小為 '2 * (stack->size) * sizeof(Element)' 字節,但可能會寫入 '2' 字節。
事情是代碼工作正常,它編譯。
這是一個警告,表示緩沖區可能會溢出,並試圖警告您在生產代碼中添加更多檢查。 這不一定是錯誤。 如果確實溢出了緩沖區,則在運行時會出現異常,即Stack corruption around local variable ...
調試程序,看看是否有類似的異常出現。 如果不是,那么您沒有超出緩沖區的界限。
我已經檢查了錯誤的詳細信息,理論上“大小”可以是 0,但默認值是 1,它永遠不會是 0。
我剛剛添加了一個大小不為 0 的檢查,然后它就消失了。
謝謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.