我的构造函数的目标是:
打开一个文件 读入特定字符串之间存在的所有内容(" %%%%%") 将每个读取行放在一个变量(历史记录)中 将final变量添加到char(_stories)类型的双指针 关闭文件。
然而,当我使用strcat时程序崩溃了。但我无法理解为什么,我已经尝试了很长时间而没有结果。 :/
这是构造函数代码:
Texthandler::Texthandler(string fileName, int number)
: _fileName(fileName), _number(number)
{
char* history = new char[50];
_stories = new char*[_number + 1]; // rows
for (int j = 0; j < _number + 1; j++)
{
_stories[j] = new char [50];
}
_readBuf = new char[10000];
ifstream file;
int controlIndex = 0, whileIndex = 0, charCounter = 0;
_storieIndex = 0;
file.open("Historier.txt"); // filename
while (file.getline(_readBuf, 10000))
{
// The "%%%%%" shouldnt be added to my variables
if (strcmp(_readBuf, "%%%%%") == 0)
{
controlIndex++;
if (controlIndex < 2)
{
continue;
}
}
if (controlIndex == 1)
{
// Concatenate every line (_readBuf) to a complete history
strcat(history, _readBuf);
whileIndex++;
}
if (controlIndex == 2)
{
strcpy(_stories[_storieIndex], history);
_storieIndex++;
controlIndex = 1;
whileIndex = 0;
// Reset history variable
history = new char[50];
}
}
file.close();
}
我也尝试过使用stringstream而没有结果..
编辑:忘记发布错误消息: &#34; Step3_1.exe中0x6b6dd2e9(msvcr100d.dll)的未处理异常:0xC00000005:访问冲突写入位置0c20202d20。&#34; 然后是一个名为&#34; strcat.asm&#34;的文件。打开..
祝你好运 罗伯特
答案 0 :(得分:2)
你在堆栈的某处有一个缓冲区溢出,事实证明你的一个指针是0c20202d20
(一些空格和一个-
符号)。
这可能是因为:
char* history = new char[50];
对于你想要放在那里的东西来说还不够大(或者它没有正确设置为C字符串,以\0
字符终止)。
我不完全确定为什么你认为每个高达10K的多个缓冲区可以连接成一个50字节的字符串: - )
答案 1 :(得分:1)
strcat
对空终止的char
数组进行操作。在行
strcat(history, _readBuf);
history
未初始化,因此无法保证具有空终止符。您的程序可能会读取超出分配的内存以查找'\0'
字节,并会在此时尝试复制_readBuf
。写入超出为history
分配的内存会调用未定义的行为,并且崩溃是非常可能的。
即使添加了空终止符,history
缓冲区也比_readBuf
短得多。这使得内存重写非常可能 - 您需要使history
至少与_readBuf
一样大。
或者,由于这是C ++,为什么不使用std::string
而不是C-style char
数组?