为什么我的简单C++程序使用队列和 fstream 错误到无效指针

Why is my simple C++ program working with queue and fstream erroring out into invalid pointer?

本文关键字:fstream 错误 指针 无效 队列 简单 我的 C++ 程序 为什么      更新时间:2023-10-16

这是代码的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

因为它实际上并没有返回字符串。

如果有人能说明为什么我会出现这种错误,我会很高兴地找出答案。