strcat 错误"Unhandled exception.."

strcat error "Unhandled exception.."

本文关键字:exception Unhandled strcat 错误      更新时间:2023-10-16

构造函数的目标是:

打开文件读取特定字符串("%%%%%")之间的所有内容将每个读行放到一个变量(历史)中将最后一个变量添加到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没有结果..

编辑:忘记发布错误信息:" Step3_1.exe中0x6b6dd2e9 (msvcr100d.dll)的未处理异常:0xC00000005:访问违反写入位置0c20202d20。"然后是名为"strcat"的文件。asm"打开. .

致以最亲切的问候罗伯特。

你在堆栈的某个地方有缓冲区溢出,你的一个指针是0c20202d20(几个空格和一个-符号)。

这可能是因为:

char* history = new char[50];

对于你想要放进去的东西来说不够大(或者它没有被正确设置为一个C字符串,以字符结尾)。

我不完全确定为什么你认为多达10K的多个缓冲区可以连接成一个50字节的字符串:-)

strcat对null终止的char数组进行操作。在

一行
strcat(history, _readBuf);

history是未初始化的,所以不能保证有空终止符。您的程序可能会读取超出分配的内存来寻找''字节,并在此时尝试复制_readBuf。在为history分配的内存之外写入会调用未定义的行为,并且很可能导致崩溃。

即使添加了空终止符,history缓冲区也比_readBuf短得多。这使得内存覆盖非常有可能-您需要使history至少与_readBuf一样大。

或者,既然这是c++,为什么不使用std::string而不是C风格的char数组?