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.
static int ReadBufferSize, totalChars;
static char *ReadBuffer = NULL;
ReadBuffer = (char *)malloc(ReadBufferSize);
...
//Double buffer size.
if((float)totalChars > (0.75f) * (float)ReadBufferSize)
{
char *tempBuffer = NULL;
tempBuffer = (char *)malloc(2 * ReadBufferSize);
if(tempBuffer == NULL)
free(tempBuffer);
else
{
memcpy(tempBuffer,ReadBuffer,strlen(ReadBuffer)+1);
free(ReadBuffer);
ReadBuffer = tempBuffer;
tempBuffer = NULL;
ReadBufferSize *= 2;
}
}
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, when there should now be space for 170 characters. I’ve also tried the following.
//Double buffer size.
if((float)totalChars > (0.75f) * (float)ReadBufferSize)
{
char* temp = 0;
temp = new char[2 * ReadBufferSize];
for(unsigned int i = 0; i < strlen(ReadBuffer); i++)
temp[i] = ReadBuffer[i];
temp[strlen(ReadBuffer)] = '\0';
delete[] ReadBuffer;
ReadBuffer = temp;
temp = 0;
ReadBufferSize *= 2;
}
I’ve also tried:
malloc(2 * ReadBufferSize * sizeof(char));
and:
strcpy_s(tempBuffer, strlen(ReadBuffer)+1, ReadBuffer);
Many thanks.
I figured it out. I was about to post some more of my code to give you more information when I noticed the problem. I had a “pageSize” variable that I had been using for the size of the array. Then when I wanted to start dynamically changing the size, I separated the array size from the page size by creating the “ReadBufferSize” variable. Unfortunately, I still had “pageSize” in the segment of code where I was putting characters into the array:
I’ve now changed it to
and everything seems to be working. Thanks to everyone for taking the time to look at this. I was fixated on the idea that the problem must be in the section of code for resizing the array, not elsewhere.