Allan Jiang
Allan Jiang

Reputation: 11331

Core dumped when writing to file?

Hi this is a very simple piece of code I just write for C++ file i/o practice. But I got a Segmentation Fault (core dumped) exception when I am running this. Here is my code below:

# include <iostream>
# include <string>
# include <cmath>
# include <fstream>
using namespace std;

int main()
{
double num, rad, i, angle, x, y;
char * filename;
ofstream file;
// prompt  ask for number
cout << "Enter the number of sample points: ";
cin >> num;

// prompt for circle radius.
cout << "Enter the circle radius: ";
cin >> rad;

// prompt for output file name.
cout << "Enter the output filename: ";
cin >> filename;

file.open (filename, fstream :: in | fstream :: trunc);
if(!file.is_open())
{
    cout << "Error opening file " << filename << endl;
    cout << "Exiting..." << endl;
    return 0;
}
for(i = 1; i <= num; i ++)
{
    //angle = 2 * M_PI * (i/num);
    //x = rad * cos(angle);
    //y = rad * sin(angle);
    //file << "\t" << x << "\t" << y << endl;
    file << "this is " << i << endl;
}
cout << "finished";
file.close();
return 0;
}

I am not sure where the problem is, but the error message "seg fault (core dumped)"shows up after Enter the output file name.

Thank you

Upvotes: 0

Views: 2379

Answers (2)

Benoit
Benoit

Reputation: 79155

cin >> filename will be undefined behaviour, because filename is an uninitialized pointer.

If you want to store characters, you need to allocate space for them. So you could do:

char filename[150] = {0};
cin >> filename; // OK, you provide space for 149 characters. Will still break
                 // if more characters are provided by the user.

or:

#include <string>
std::string filename; // overloads operators >> and << with streams
                      // automatically performs memory management
// std::cin >> filename; /* Would stop at first space */
std::getline(std::cin, filename); // better: will stop at any carriage return

Upvotes: 2

Akhil Thayyil
Akhil Thayyil

Reputation: 9403

Pls allocate some memory for filename, ur only using a ponter. Make the change

char  filename[50];

Upvotes: 1

Related Questions