EXC_BAD_ACCESS error when using getline() in ifstream - c++

I have been running into this EXC_BAD_ACCESS issue a lot lately when developing in C++ using Xcode. This time, I can't figure out what is wrong though.
I have this function that should be simple enough, just a way to count how many lines are in a file:
int getNumLines(string file)
{
int lineCount = 0;
string line;
ifstream textFile;
textFile.open(file);
if( textFile.is_open() && !textFile.ios_base::fail() )
{
while(getline(textFile, line))
{
lineCount++;
}
}
textFile.close();
return lineCount;
}
Every time I run my code, I get this line of errors leading back to the fstream class file, and the error code:
Thread 1: EXC_BAD_ACCESS (code=1, address=0x7000000070)
Here is where this error leads:
I'm not sure what's causing this issue. Zombie objects don't seem to help me find the source of the problem, or perhaps I am just not understanding how to enable them properly.

Thanks for all your help. I found the issue to be how I was handling arrays in the objects I created. I moved everything over to std::array instead of int* and my memory errors went away.

Related

Issue reading multiple lines from .txt file in C++

I'm trying to create a student database system for a school project. I'm trying to create a function that will search a .txt file for the student id and return all of the other variables on the string. This is working great if I search for the id of the student on the first line of the txt file but isn't capturing anything if I search for a student on another line. Am I missing something obvious?
The student data is 16 strings delimited by commas on each line. The student ID is the first string.
Thanks for any assistance!
StudentType findStudent(int studentToFind)
{
ifstream inFile;
inFile.open("students.txt");
string currentLine;
string dataRead[16];
istringstream is;
int currentStudent;
if (inFile)
{
while (getline(inFile, currentLine))
{
is.str(currentLine);
for (int i = 0; i < 16; i++)
{
getline(is, dataRead[i], ',');
}
currentStudent = stoi(dataRead[0]);
if (currentStudent == studentToFind)
{
/*
Do stuff here
*/
inFile.close();
return foundStudent;
}
cin.ignore(); // Not sure if this is needed but I was trying to
// clear the \n char if that was causing the issue
}
}
}
First : you aren't using cin, so get rid of cin.ignore().
Second : you should make sure you ALWAYS close infile at the end... so I would suggest not returning early or closing early, but using a break statement to exit your loop and then have a single return of whether you found it or not.
Third: Now that you removed all the 'gorp' we can finally hone in on the problem ... effectively the question is do we read all the lines?
Well let's check that, try printing out currentLine each time at the beginning of the while loop, if you know currentLine is updated properly, is is getting updated each time? yes...
ok then look at your next loop let's print out currentStudent each time... does currentStudent print the right value for each line? i.e. is the getline write into dataRead[i] actually writing what you think it should be to the right space?
Did you find the problem yet?
This is the kind of problem you need to learn how to solve yourself using print statements and a debugger. That what its for. If you are in visual studio run in debug mode and step through it... if not, use gdb. learn it and get used to it, you'll be using it a lot!
good luck

How to read individual lines of a text file using C++

Ok, so its been a while since i messed with reading and writing file and i have just about forgot everything i learned. So, i am currently just trying to figure out how to read specific lines from a text file and output that said line into the command prompt. Here is my code that i am having issues with:
#include <iostream>
#include <fstream>
using namespace std;
int main(){
ifstream input;
int lineN=0;
string line[lineN];
input.open("input.txt");
getline(input, line[lineN]);
cout << line[lineN];
}
As it currently is, it will read the first line of the text file no problem. However, if i change the variable lineN(which stands for line number) to 1 to read the second line, it crashes the prompt. I have no idea what it is i am doing wrong. I have tried researching this problem, but everyone's answer is too vague (That or i'm just too dumb). If you could help me out that would great.
The problem is that you define here an empty array of strings and arrays are not dynamic:
int lineN=0;
string line[lineN];
When you change lineN to 1, nothing changes in the array, and you'll get out of bound !
The bettter way would be to use vectors:
vector<string> line;
Read in a temporary string:
string current_line;
getline(input, current_line);
and add it to your vector:
line.push_back(current_line);
Putting all this in a nice loop would be more useful:
string current_line;
while (getline(input, current_line)) {
line.push_back(current_line);
}
You may access any line later, by using line[i] exactly with your array, as long as i< line.size(). Or you may iterate easily throug all its content:
for (string x : line) { // means for every x in line[]
cout<< x<<endl;
}
you allocate a array of size 0 ...
you will find answer of what will happen can be found here:
C++ new int[0] -- will it allocate memory?

Loading Files Results in Program Stop Working

I was wondering if anyone could help me with my code (C++)? This is the function that will not work. When I run it, Windows pops up and says "This program has stopped working." Here is the code that will not run (it's a little long, but the program is proprietary and I appreciate any help):
void ClassName::loadGrades(){
string temp;
int count=0;
ifstream labErnIn("labGradesErn.txt");
if(labErnIn.is_open()){
count=0;
while(labErnIn.good()){
getline(labErnIn, temp);
float tempF = ::atof(temp.c_str());
labGradesErn[count] = tempF;
if(labGradesErn[count]==0 && count==0) labGradesErn[count]=-1;
count++;
}
labGradesErn[count-1]=-1;
labErnIn.close();
}
else{
cout << "Unable to open file labGradesErn.txt" << endl;
}
// I repeat this for three other sections, same code, different var names.
// From 'ifstream...' to 'Unable to open file'
}
All variables not declared in this function are declared elsewhere.
Thanks, I really appreciate any and all help!
If labGradesErn is a fixed array, you risk an array overrun sooner or later. If it is a std::vector, you should use push_back() to append elements, because increasing the index doesn't increase the vector.
Another point is your while loop. You don't test if getline succeeds and you should loop on getline instead of good
while (getline(labErnIn, temp)) {
...
}

Two Identical Code Segments, Different Results

All I need to do is a simple read from a file in the same directory, but for some reason it refuses to work.
It works perfectly fine in this quick test one I made after I had problems, and outputs the number of entries in the text file.
#include <iostream>
using std::cout;
using std::cin;
#include <cstdio>
int main()
{
int a;
int b = 0;
freopen ("7.txt", "r", stdin);
while (cin >> a)
++b;
cin.clear();
fclose (stdin);
freopen ("7.txt", "r", stdin);
cout << b << '\n';
fclose (stdin);
}
EDIT: Wow I'm sorry to everyone who tried wrapping their heads around this. It was pretty late when I posted this, but I thought I finished. Apparently not. Now upon reopening my file to post the code in it, I realize that I moved everything into a folder before, but apparently when I tried to run the actual thing, it saved back outside of the folder, so it couldn't open "7.txt".
Problem solved I guess, sad waste of space seeing as how it wasn't even complete O_o, sorry.
EDIT2: Okay now I'm confused. I had a temp account on this computer, but when I logged into this account to ask a different question, this one as I meant to post it the other night showed up. I wasn't even on this computer while asking it. Not sure why it wasn't posted like that if it was all ready to be though.
My best "guess" is that you are trying to re-read the same file. If this is the case then you could try this :
std::ifstream file("7.txt");
std::string line = "";
while(std::getline(file, line))
{
//do something
}
//reset file pointer
file.clear();
file.seekg (0, std::ios::beg);
//re-read file
while(std::getline(file, line))
{
//do something else
}
Please try and formulate better questions in the future.
I have no idea what you're trying to do, but any interaction between freopen, fclose and cin is implementation defined at best (and most likely undefined behavior).

"An access violation (Segmentation Fault) raised in your program."

My C++ program compiles and works up until I call this function from main():
int uword(){fstream infile("numbers.txt");
fstream exfile("wordlist.txt");
string numb[numoflines];
string lines[numoflines];
number = 1;
line = 1;
for(int i=0;i<numofline;++i)
{
getline (infile,number);
numb[i] = number; //I think this is causing the problem
getline (exfile,line);
lines[i] = line; //This too
}
infile.close();
exfile.close();
string yourword;
Something here causes it to crash, in the debug it pops up with "An access violation (Segmentation Fault) raised in your program."
EDIT: My mistake was using !infile.eof in the for loop.
Not a direct answer, but I believe it's a good one...
Use The Debugger! GDB should suspend at the exact line when the segmentation fault happens, thus giving you a very good hint about what the error is.
The getline function does not work the way you think it works.
Also, there could be more than numoflines lines in infile.