C++: cin >> *char

ubsan picture ubsan · Jul 6, 2013 · Viewed 7k times · Source

So, I'm currently writing a line editor as a learning project on I/O, writing files, and the like. It is written in C++, and I am currently trying to write out to a file of the user's choosing. I have CLI arguments implemented, but I currently have no idea how to implement an in program way of specifying the file to write to.

char *filename;
if (argc >= 2){
        filename = argv[1];
} else{
        cout << "file>";
        cin >> filename;
        cin.ignore();
}

This works perfectly well when I use command line arguments; however, whenever I do not, as soon as I start the program, it Segmentation Faults. The place where I use the actual filename is in the save command:

void save(char filename[], int textlen, string file[]){
        ofstream out(filename);
        out << filestring(textlen, file);
        out.close();
}

Which also works perfectly well. Is there any way you can help me? Full source code, for review, is up on https://github.com/GBGamer/SLED

Answer

BoBTFish picture BoBTFish · Jul 6, 2013

The problem is that char* filename is just a pointer to some memory containing characters. It does not own any memory itself. When you use the command line argument, the program handles storing that string somewhere, and you get a pointer to it. When you try to read using cin >> filename there isn't actually anywhere to store the read data.

Solution: Replace char* filename with std::string filename (and #include <string>).

Then to open the output file, you need a c-style string (null terminated char array). std::string has a function for this. You would write

std::ofstream out(filename.c_str());
                           ^^^^^

Or, in fact, if you can use a recent compiler with c++11 features, you don't even need to use c_str(). A new std::ofstream constructor has been added to accept a std::string.