C++ 字符数组的动态内存分配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8372577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamic memory allocation for character arrays
提问by devjeetroy
Okay, so I was trying to resize an array as follows :
好的,所以我试图按如下方式调整数组大小:
if((editBufferCounter + 20) > editBufferSize)
{
char* temp;
temp = new char[editBufferSize + 5];
strcpy(temp, editBuffer);
delete[] editBuffer;
editBufferSize *= 2;
editBuffer = new char[editBufferSize];
strcpy(editBuffer, temp);
delete[] temp;
}
The last line delete[] temp
causes a memory problem. The program simply crashes. I can't seem to get what the problem here is.
最后一行delete[] temp
导致内存问题。该程序只是崩溃。我似乎不明白这里的问题是什么。
Note:
The program runs fine if i remove the line delete[] temp;
注意:如果我删除该行,程序运行良好 delete[] temp;
回答by arnkore
Do your editBuffer have a terminating NUL character? if not, please replace strcpy
with strncpy
.
您的 editBuffer 是否有终止 NUL 字符?如果不是,请替换strcpy
为strncpy
。
回答by Blastfurnace
You function can be simplified to:
您的功能可以简化为:
if ((editBufferCounter + 20) > editBufferSize)
{
char* temp = new char[editBufferSize * 2];
std::copy_n(editBuffer, editBufferSize, temp);
delete[] editBuffer;
editBufferSize *= 2;
editBuffer = temp;
}