Segmentation Fault while Reading from File - c++

I am trying to print last 10 lines of a file. Following is my code, but it is giving a segmentation fault due to fscanf. While running with gdb the fault reads : vfscanf.c: No such file or directory.
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
int main()
{
FILE *fp = fopen("microfile.txt","r");
char *c[10];
int idx = 0;
cout<<fp<<"\n";
while(!feof(fp))
{
if(idx<10)
{
fscanf(fp,"%s",c[idx]);
idx++;
}
else if(idx==10)
{
for(int i=0;i<idx-1;i++)
{
c[i] = c[i+1];
}
fscanf(fp,"%s",c[idx-1]);
}
}
int i=0;
while(i<10)
{
cout<<c[i]<<"\n";
i++;
}
}

The source of the problem comes from the fact you have an array of pointers on this line:
char* c[10];
And later on in the program you attempt to assign character values to these pointers. Maybe you meant for just an array of characters instead:
char c[10];
Moreover, use of the Standard library is recommended. Try using std::string and standard streams and your program can be made more maintainable:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string s;
s.assign(
std::istreambuf_iterator<char>(std::ifsteam("microfile.txt").rdbuf()),
std::istreambuf_iterator<char>());
for (char c : s)
std::cout << c << std::endl;
}

Related

c++ : char* invariably stores the word vector

This is although a code specific question but the output is quite bizarre.
I am aware of STL string etc. I was fooling around when I noticed something strange, and could not find a reason for it. :(
See the Two Codes below and the output.
[Code #1] (https://ideone.com/ydB8sQ)
#include <iostream>
#include <vector>
#include <cstdlib>
#include <cstdio>
using namespace std;
class str
{
private:
vector<char> A;
public:
str(const char *S) {
int sz = sizeof(S);
cerr << sz << endl;
for (int i = 0; i < sz; ++i) {
cout << S[i];
//A.push_back(S[i]); //!-- Comment --!//
}
}
};
int main(int argc, char const *argv[])
{
str A("");
return 0;
}
In this, An Empty String is passed and is printed. The Vector A does nothing but is relevant to this problem. In the first version, A is untouched, and the code prints garbage value. (see ideone O/P)
In this second version ( see A.push_back is now uncommented )
[Code #2] (https://ideone.com/PPHGZy)
#include <iostream>
#include <vector>
#include <cstdlib>
#include <cstdio>
using namespace std;
class str
{
private:
vector<char> A;
public:
str(const char *S) {
int sz = sizeof(S);
cerr << sz << endl;
for (int i = 0; i < sz; ++i) {
cout << S[i];
A.push_back(S[i]);
}
}
};
int main(int argc, char const *argv[])
{
str A("G");
return 0;
}
The Output is :
Gvector
This is across GCC / MinGW x64. This one never prints garbage value but always contains the word 'vector'.
Where is the char* in the function pointing to?
Why would 'vector' be there anyways?
Also, the size of char * is 8.
EDIT : This does not happen if it isn't wrapped around a 'class'.
The word 'vector' appears always. I supposed it was random garbage value but then how come ideone still has the same word in its memory?
The main problem in your code is in line int sz = sizeof(S);. sizeof(S) is always equal to sizeof(char *) which seems to be 8 on your system. sizeof gives you number of bytes for variable itself. If you want to know number of bytes in string to which your char pointer points, you should use strlen function instead.
You get that vector string in output randomly, as you are accessing memory which is not in allocated space. Accessing such memory is undefined behavior, so you get your undefined result.

Segmentation fault in reversing string program

I am trying to reverse a string. Can someone explain me why this is giving me segmentation fault?
#include <iostream>
#include <string>
using namespace std;
int main(){
string str,rstr;
int len=str.length(),i=0;
cin>>str;
while(str[i]!='\0'){
rstr[--len]=str[i++];
}
rstr[str.length()]='\0';
cout<<rstr;
return 0;
}
P.S.: Need to reverse it without using library functions.
If you want to go the way you are doing it, for practice purposes, try this changes and start from there
#include <iostream>
#include <string>
using namespace std;
int main(){
string str,rstr;
cin>>str; // --- Moved this line up
rstr = str; // --- Added this line
int len=str.length(),i=0;
while(str[i]!='\0'){
rstr[--len]=str[i++];
}
rstr[str.length()]='\0';
cout<<rstr;
return 0;
}
Or just use reverse iterator
std::string s = "Hello";
std::string r(s.rbegin(), s.rend());
str is nothing but a declared string here:
int len=str.length(),i=0;
So you can't do str.length()
Do something like:
#include <iostream>
#include <string>
using namespace std;
int main(){
string str,rstr;
int len,i=0;
cin>>str;
len = str.length();
while(str[i]!='\0'){
rstr[i++]=str[--len];
}
rstr[str.length()]='\0';
cout<<rstr;
return 0;
}

C++ Array pointer-to-object error

I am having what seems to be a common issue however reading through the replies to the similar questions I can't find the solution to my issue at all as I have already done what they are suggesting such as making the variable an array. I have the following code:
#include "stdafx.h"
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
#include <algorithm>
#include <future>
using namespace std;
string eng2Str[4] = { "money", "politics", "RT", "#"};
int resArr[4];
int main()
{
engine2(eng2Str[4], resArr[4]);
system("Pause");
system("cls");
return 0;
}
void engine2(string &eng2Str, int &resArr)
{
ifstream fin;
fin.open("sampleTweets.csv");
int fcount = 0;
string line;
for (int i = 0; i < 4; i++) {
while (getline(fin, line)) {
if (line.find(eng2Str[i]) != string::npos) {
++fcount;
}
}
resArr[i] = fcount;
}
fin.close();
return;
}
Before you mark as duplicate I have made sure of the following:
The array and variable I am trying to assign are both int
Its an array
The error is:
expression must have pointer-to-object type
The error is occurring at the "resArr[i] = fcount;" line and am not sure why as resArr is an int array and I am trying to assign it a value from another int variable. I am quite new to C++ so any help would be great as I am really stuck!
Thanks!
The problem is that you've declared your function to take a reference to a single string and int, not arrays. It should be:
void engine2(string *eng2Str, int *resArr)
or:
void engine2(string eng2Str[], int resArr[])
Then when you call it, you can give the array names as arguments:
engine2(eng2Str, resArr);
Another problem is the while loop in the function. This will read the entire file during the first iteration of the for() loop. Other iterations will not have anything to read, since it will be at the end of the file already. You could seek back to the beginning of the file, but a better way would be to rearrange the two loops so you just need to read the file once.
while (getline(fin, line)) {
for (int i = 0; i < 4; i++) {
if (line.find(eng2Str[i]) != string::npos) {
resArr[i]++;
}
}
}
I would suggest to use std::vector instead of pure C array.
In your code, there are more issues.
You are passing the fourth element of both arrays to the engine2 function.
From your definition of void engine2(string &eng2Str, int &resArr) you expect reference to a string (not array / vector) and an address / reference of int - you need to pass an pointer to the first element of resArr.
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <future>
using namespace std;
vector<string> eng2Str = { "money", "politics", "RT", "#" };
int resArr[4] = {};
void engine2(const vector<string>& eng2Str, int* resArr)
{
ifstream fin;
fin.open("sampleTweets.csv");
int fcount = 0;
string line;
for (int i = 0; i < 4; i++)
{
while (getline(fin, line))
{
if (line.find(eng2Str[i]) != string::npos)
{
++fcount;
}
}
resArr[i] = fcount;
}
fin.close();
return;
}
int main()
{
engine2(eng2Str, resArr);
system("Pause");
system("cls");
return 0;
}

Failed to generate disassembly for stack frame because the URL cannot be translated & Segmentation fault: 11

I am still a newbie in programming. I am writing a program of 2D Snell's Law. I know the problem may due to wrong localisations in Xcode, but I am writing in C++ only and g++ even gives me segmentation fault error after compiling successfully.
Here are my code for main function:
#include <string>
#include "Snell.hpp"
int main(int argc, const char * argv[]){//thread 1 exc_bad_access (code=2 address=0x7fff5f238304)
string filename;
double time;
Snell S[3600];
for (int i=1; i<=1; i++) {
while (S[i].angle_tr>0) {
filename="VPVSMOD"+to_string(i)+".txt";
S[i].Open(filename);
time=S[i].Locate(i);
cout<<"The "<<i<<"th event takes "<<time<<" seconds to reach the destination"<<endl;
S[i].angle_tr-=0.01;
}
}
return 0;
}
Here is the code for Snell.hpp
#ifndef Snell_hpp
#define Snell_hpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <string>
#include <algorithm>
#include <cmath>
using namespace std;
class Snell{
private:
double GetV(double lat,double dep);
int ny,nz,time;
double la[30],h[20],v[10][30];
double lat,alt,step;
public:
Snell();
void Open(string filename);
double Locate(int i);
double angle_tr;
};
#endif /* Snell_hpp */
and Snell.cpp:
#include "Snell.hpp"
Snell::Snell(){
ny=1,nz=3,time=0;
lat=0,alt=0,step=1;
angle_tr=M_PI/2;
}
void Snell::Open(string filename){
ifstream fin(filename);
stringstream ss;
string str,tok;
for (int i=0; i<nz; i++) {
(getline(fin, str));
ss.str(str);
for (int j=0; j<ny; j++) {
getline(ss, tok, ',');
v[i][j]=stod(tok);
cout<<v[i][j]<<",i="<<i<<",j="<<j<<endl;
}
ss.clear();
}
fin.close();
angle_tr=v[1][0]/v[0][0];
}
double Snell::GetV(double lat, double dep){
int index_la = 0,index_dep = 0;
index_dep=round(dep);
return (v[index_dep][index_la]+v[index_dep+1][index_la])/2;
}
double Snell::Locate(int i){
string filename;
double count_t=0;
double latt=lat,altt=alt,step_altt_all=0,angle=0,angle_p=0;
double vsy,vsz;
double vs,vs_n;
ofstream fout;
angle=M_PI/2-atan(angle_tr);
vs=GetV(lat, alt);
filename="Test"+to_string(i)+"_"+to_string(time)+".txt";
fout.open(filename,ios::out);
fout<<lat<<","<<alt<<endl;
while (altt!=2) {
//cout<<"Compute Velocity in each dimension"<<endl;
angle_p=angle;
vsy=vs*cos(angle);
vsz=vs*sin(angle);
//cout<<"Check Velocity"<<endl;
if (vsy==0||vsz==0) {
break;
}
//cout<<"Compute reflection point"<<endl;
step_altt_all=step/vsz;
count_t=count_t+step/vsz;//time plus one
latt=latt+vsy*(step_altt_all);
step_altt_all=0;
altt=altt+step;
//cout<<"Compute New Velocity"<<endl;
vs_n=GetV(latt,altt);
if ((vs_n*cos(angle)/vs)>1) {
break;
}
else{
angle=M_PI/2-asin(vs_n*cos(angle)/vs);
vs=vs_n;
if (angle!=angle_p)
fout<</*"position:"<<*/latt<<","<<altt<<endl;
}
}
fout.close();
filename="Result"+to_string(i)+"_"+to_string(time)+".txt";
fout.open(filename);
fout<<0<<" "<<latt<<" "<<altt<<" "<<step<<endl;
fout.close();
return count_t;
}
My immediate guess is: You must have blown your stack. Please see why is stack memory size so limited?
....And yes, On my platform, my guess was correct...
Reproducing your program, but modifying your main.cpp ...
int main(int argc, const char * argv[]){//thread 1 exc_bad_access (code=2 address=0x7fff5f238304)
string filename;
double time;
//Snell S[3600];
std::cout << sizeof(Snell) << " bytes" << std::endl;
return 0;
}
It gives an output of
2848 bytes
....And You are trying to allocate 3600 of them... ~10MB!!
The solution to that is to allocate it on the heap using a std::unique_ptr or better still, your good friend, std::vector.
Modify your main to this
#include <string>
#include <memory>
//or #include <vector>
#include "Snell.hpp"
int main(int argc, const char * argv[]){//thread 1 exc_bad_access (code=2 address=0x7fff5f238304)
string filename;
double time;
std::unique_ptr<S[]> p(new Snell[3600]);
//or std::vector<Snell> S(3600);
for (int i=1; i<=1; i++) {
while (S[i].angle_tr>0) {
filename="VPVSMOD"+to_string(i)+".txt";
S[i].Open(filename);
time=S[i].Locate(i);
cout<<"The "<<i<<"th event takes "<<time<<" seconds to reach the destination"<<endl;
S[i].angle_tr-=0.01;
}
}
return 0;
}

conversion string to character in c++ Not Working Properly

make a function which receive the file name but it not working properly because it receives "Doctor.txtG" but I am giving "Doctor.txt" how can i resolve it?My code is Given below......
#include <iostream>
#include <conio.h>
#include <fstream>
using namespace std;
int number_of_lines = 0;
int numberoflines(string A);
int main()
{
cout<<numberoflines("Doctor.txt");
getch();
return 0;
}
int numberoflines(string A)
{
int Len;
char Chr[Len];
Len=A.length();
A.copy(Chr, Len);
//cout<<Len;
cout<<Chr;
string line;
ifstream myfile(Chr);
if(myfile.is_open())
{
while(!myfile.eof())
{
getline(myfile,line);
number_of_lines++;
}
myfile.close();
}
return number_of_lines;
}
It needs to copy a null-terminated byte into Chr.
Use
strcpy(Chr, A.c_str());
instead of A.copy(Chr, Len);
And you should properly init Chr like
char Chr[1024]
or
char* Chr = new char[Len + 1].
Your problem is happening because you are trying to create a char array with the size Len. But you have not initialized Len before using it. This is why it is resulting in undefined behavior and creating this problem. Always try to initialize variables when you declare them. Otherwise, this problem will happen quite often.
However, You don't need to create another char array. Just use std::string::c_str(); in your parameter for the constructor of the ifstream. I am giving a sample code below. This should solve your problem.
#include <iostream>
#include <conio.h>
#include <fstream>
using namespace std;
int number_of_lines = 0;
int numberoflines(string A);
int main()
{
cout<<numberoflines("Doctor.txt");
getch();
return 0;
}
int numberoflines(string A)
{
string line;
ifstream myfile(A.c_str());
if(myfile.is_open())
{
while(!myfile.eof())
{
getline(myfile,line);
number_of_lines++;
}
myfile.close();
}
return number_of_lines;
}