为什么我的简单C++程序使用队列和 fstream 错误到无效指针
Why is my simple C++ program working with queue and fstream erroring out into invalid pointer?
这是代码的github要点,如果愿意,我也可以将代码附加到这个问题中。
https://gist.github.com/alevnyaa/e917bc2aa1e72aa210d8cff9fa5e922b
当我在 Linux 上使用 g++ 6.3 和 c++11 编译并运行这个程序时,在完成前几行后,程序在第 62 行调用print_queue后崩溃。由于我什至没有手动使用指针或内存,因此我不知道这里的问题是什么。
*** Error in `./a.out': free(): invalid pointer: 0x0000000000606160 ***
我可以尝试任何建议。我假设我没有注意到一个简单的问题,但是在看了太多次之后,我被蒙蔽了。
谢谢
这是代码:
首先是文件D301.txt
D301 Capacity 40
1 1 5
2 2 4
3 3 4
4
5 2
6
7 1
如果队列.cpp
#include <fstream>
#include <iostream>
#include <queue>
void stoq(std::queue<char>& q, std::string s){
std::queue<char> empty;
std::swap(q, empty);
for(char ch : s){
if(!isspace(ch)){
q.push(ch);
}
}
}
std::string print_queue(std::queue<char> q){
std::cout << "Queue: ";
int i = 0;
while(!q.empty()){
std::cout << "i" << i;
i++;
std::cout << q.front();
q.pop();
}
std::cout << std::endl;
}
int main(){
std::fstream infile("D301.txt");
std::string line;
std::queue<char> q;
std::getline(infile, line);
stoq(q, line);
print_queue(q);
std::string classroom_name;
while(q.front() != 'C'){
classroom_name += q.front();
q.pop();
}
for(int i=0; i<8; i++){
q.pop();
}
std::string capacity_str;
while(!q.empty()) {
capacity_str += q.front();
q.pop();
}
int capacity = stoi(capacity_str);
std::getline(infile, line);
while(infile){
std::getline(infile, line);
std::cout << "fl" << std::endl;
stoq(q, line);
std::cout << "sl" << std::endl;
print_queue(q);
std::cout << "tl" << std::endl;
}
infile.close();
}
-1真的有保证吗?
当队列为空时会发生什么?
while(q.front() != 'C'){
classroom_name += q.front();
q.pop();
}
如果队列的元素少于 8 个,会发生什么情况?
for(int i=0; i<8; i++){
q.pop();
}
我
不确定为什么会有这样的错误。但是,该修复程序似乎正在更改功能:
标准::字符串print_queue
到
无效print_queue
因为它实际上并没有返回字符串。
如果有人能说明为什么我会出现这种错误,我会很高兴地找出答案。
相关文章:
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么当我在 std::string 中打开文件名的 fstream 时出现"no matching function"错误?
- C++ 错误检查 fstream open() 命令和一般字符串流错误处理
- 变量 std::fstream 文件具有初始值设定项,但类型不完整 编译错误
- std::fstream 已使用,但编译器抛出错误
- 为什么错误"permission denied","id returned 1 exit status"仅在 IM 使用 C++ 中的头文件 fstream 时才出现
- fstream.h 中的 STL 命名空间错误与 qmake/make.
- 为什么我的简单C++程序使用队列和 fstream 错误到无效指针
- C Fstream字符串组合错误
- Fstream中的写功能将在Windows 10上引起错误
- fstream错误无法在C 中创建或打开文件
- CMD窗口停止工作,文本文件使用fstream读取错误
- 在结构中使用fstream,错误
- Ubuntu 13.10 中的 GCC iostream fstream 错误
- 如何在将 fstream 数据写入磁盘时检测致命错误
- 编译器C++中的 fstream 错误
- 在c++中使用同一个fstream对象进行读写时,是否有任何导致错误的特性
- fstream 错误,"streambuf"当我尝试编译和运行时
- c++中的fstream错误
- 使用Cygwin编译时出现fstream错误