I'm resizing an array. The resize (doubling the size) appears to work correctly, but when I send more text into the resized array, when it reaches what would have been the limit of the array before it was resized, I get a "Debug Assertion Failed! Expression: (L"Buffer is too small" && 0)" error. I've tried it a few different ways, always with the same result.
For my testing, ReadBufferSize has been set initially to 85 characters. After the code resizing the array is executed, the text in ReadBuffer is still displayed on the screen. I type more characters and they are sent into the array, and from there, displayed on the screen. But when the number of characters reaches 85 characters, I get the "Debug Assertion Failed! Expression: (L"Buffer is too small" && 0)" error. I've also tried the following.
Because malloc() takes the size in bytes, and I'm creating a char array, multiplying ReadBufferSize by sizeof(char) was multiplying it by 1, which seemed redundant. But in my efforts to get the code to work I have tried
malloc(2 * ReadBufferSize * sizeof(char));
but it didn't make any difference. ReadBufferSize is an int, and so is totalChars.
This debug message is detected when the program frees the buffer, not when the overflow actually occurs (it puts some sentinal values before and after the buffer in memory, and checks if they have been overwritten when the bufer is freed).
If you get it at the first time it is trying to resize, that means the problem is on the initial buffer libreation, not when you copy new data in the new one, and it means the problem has occured before the resizing code.
What happened to all the comments that appeared in this thread yesterday?
I actually figured out what the problem was. The array resizing wasn't the problem; it was working fine. The problem was the code adding characters to the array after it was resized.
Originally, the size of the array was set by a variable called "pageSize" based on the number of average characters that would fit on the screen. When I decided to dynamically resize the array, I created a new variable: "ReadBufferSize" that was independent of the page size. Unfortunately I left the reference to pageSize in the code for responding to keyboard input.
strcat_s(ReadBuffer, pageSize, keystroke);
When it thought it had overrun based on "pageSize" it threw up the error. I replaced "pageSize" with "ReadBufferSize" and now it all seems to work fine.
strcat_s(ReadBuffer, ReadBufferSize, keystroke);
So yes, the problem never would have arisen if I'd used strcat() instead.
Thankyou all for having a look at this. I'll mark it as solved now.