我正在调整数组的大小。调整大小(将大小加倍)似乎可以正常工作,但是当我将更多文本发送到调整大小的数组时,当它达到调整大小之前数组的限制时,我得到一个“调试断言失败!表达式: (L"缓冲区太小" && 0)" 错误。我尝试了几种不同的方法,总是得到相同的结果。
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;
}
}
对于我的测试,ReadBufferSize 最初设置为 85 个字符。在执行了调整数组大小的代码后,ReadBuffer 中的文本仍然显示在屏幕上。我输入更多字符,它们被发送到数组中,然后从那里显示在屏幕上。但是当字符数达到 85 个字符时,我收到“Debug Assertion Failed! Expression: (L"Buffer is too small" && 0)”错误,此时应该有 170 个字符的空间。我也试过以下。
//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;
}
我也试过:
malloc(2 * ReadBufferSize * sizeof(char));
和:
strcpy_s(tempBuffer, strlen(ReadBuffer)+1, ReadBuffer);
非常感谢。