在c++代码中找不到错误

Cannot find the error in C++ code

本文关键字:找不到 错误 代码 c++      更新时间:2023-10-16

这段代码有什么问题吗?这是读取数据库数据函数的一部分。o为数据库输出流的otl_stream对象。我的导师告诉我,我在这段代码中有错误,我是c++的新手,不知道是什么问题…我必须使用指针,所以请不要告诉我使用静态char数组。

char* temp_char;
while (!o.eof()) {
   temp_char = new char [31];
   o>>temp_char;
   records.push_back(temp_char);
   delete[] temp_char;
}

o.eof()仅在您尝试读取流的末尾后才变为true,因此您不应该使用while(!o.eof())进行循环控制。

除非recods.push_back(temp_char)复制了指向数组,否则records将在delete[] temp_char;之后包含一个悬空指针

while(true) {
    temp_char = new char[31];
    o >> temp_char;
    if (!o) {
        delete[] temp_char;
        break;
    }
    records.push_back(temp_char);
}

看起来更好(尽管我确定这不是习惯用法)。

当然,使用std::string可以减轻内存管理的负担。

我不会在每次读取一个单词时重新分配字符串。如果最后一次迭代读到空格,则返回一个空字符串。

    char* temp_char = new char[BUF_SZ];
    while ( ! o.eof() ) {
       o>>temp_char;
if( *temp_char != '' ) // If not an empty string
       records.push_back(temp_char);
    }
    delete[] temp_char;