在c++代码中找不到错误
Cannot find the error in C++ code
这段代码有什么问题吗?这是读取数据库数据函数的一部分。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;
相关文章:
- 我在c ++矩阵计算器程序中找不到错误
- 我在代码中找不到错误以找到最大的素因数?
- 在我的应用逻辑中找不到错误
- 在模板类中找不到错误
- 双重释放或损坏错误(找不到错误?
- 在我的 cpp 或头文件中找不到错误,类构建失败
- 在哈希表复制构造函数中找不到错误
- 找不到错误。C++,字符串
- 8谜题代码.我的队列没有填充,我找不到错误的位置
- C++中的预期表达式,但找不到错误
- C++ 将布尔隐式转换为 int 和算术,删除分支,找不到错误
- 找不到错误"invalid conversion from char to const char*"的解决方案
- 在以下代码中找不到错误:- 在 try() 之前预期未限定 id
- 在重载运算符中找不到错误<
- C++ 中的分段错误(核心转储) 找不到错误
- 在使用set_difference算法时找不到错误
- 在 while 循环中找不到错误?
- C++错误LNK2001,找不到错误
- 在我的代码中找不到错误....分段错误
- LNK2005(已定义)找不到错误