Reputation: 123
Here is a github gist of the code, if preferred I can append the code to this question too.
https://gist.github.com/alevnyaa/e917bc2aa1e72aa210d8cff9fa5e922b
When I compile and run this program with g++ 6.3 with c++11 on linux, after working through the first few lines the program crashes after print_queue is called at line 62. As I am not even manually working with pointers or memory, I have no idea what the problem here is.
*** Error in `./a.out': free(): invalid pointer: 0x0000000000606160 ***
I can try any suggestions. I am assuming that I am not noticing a simple problem, but I am blinded after looking at it too many times.
Thank you
Here is the code:
Firstly the file D301.txt
D301 Capacity 40
1 1 5
2 2 4
3 3 4
4
5 2
6
7 1
ifqueue.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();
}
Was the -1 really warranted?
Upvotes: 0
Views: 429
Reputation: 123
I am unsure as to why the error was as such. However, the fix seems to be changing the function:
std::string print_queue
into
void print_queue
As it isn't actually returning a string.
If anyone can pitch in why I was getting that kind of error, I'll be happy to find out.
Upvotes: 1
Reputation: 1099
What happens when the queue is empty?
while(q.front() != 'C'){
classroom_name += q.front();
q.pop();
}
What happens if the queue has less than 8 elements?
for(int i=0; i<8; i++){
q.pop();
}
Upvotes: 1