问题
- Function Name: expandStack
- Input: a pointer to a Stack type (Stack*)
- Output: none
- Function Operation: The function expands a 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;
}
In this line: expandedStack[i].c = stack->content[i].c; I get a "green warning" saying: "c6386 buffer overrun while writing to 'expandedStack': The writeable size is '2 * (stack->size) * sizeof(Element)' bytes, but '2' bytes might be written.
The thing is that the code works fine, it compiles.
回答1:
This is a warning that says that the buffer could be overrun and is trying to warn you to add some more checks in your production code. It is not necessarily an error. If you did overrun the buffer, you would have an exception during run time, which would say Stack corruption around local variable ...
Debug the program, and see if any exception like that comes up. If not, then you are not exceeding the buffer's bounds.
回答2:
I've checked the details of the error, 'size' could theoritically be 0 but the default value is 1 and it would never be 0.
I just added a check that size isn't 0 and it disappeared.
Thanks!
来源:https://stackoverflow.com/questions/59617660/c6386-buffer-overrun-while-writing