Ratata Tata
Ratata Tata

Reputation: 2879

fopen get error with char * in c++

There is a function to load files:

int loadfile(char *fn)
{
    printf( "\n my path: '%s' \n", fn );
    FILE *f = fopen( fn, "r");
    printf( "got\n" );

    ...

    return 1;
}

The first file is in main() newfile( argv[1] );, works. The second is get by flex parsing/reading the first file, what I belive isn't related to the problem.

The console:

path: 'file1.hot' 
got
path: 'file2.hot' 
Segmentation fault: 11

The printf was able to print the char *fn, but fopen get a segmentation fault.

The next situation was, I tried explicit to put the file inside the loadfile doing fopen( "file2.hot", "r"); and works.

I'm compiling with g++, there is a different approaching when using c++ to use char * or fopen?

EDIT

Sorry, there's no newfile( argv[1] );. Correct: loadfile( argv[1] );.

Upvotes: 0

Views: 1486

Answers (3)

codeling
codeling

Reputation: 11418

General remark: When using C++, please prefer std::fstream to the C-style fopen/fread/etc.; also prefer std::string to char*. The latter alone will cure many memory headaches. If you, for some reason, have to stick to the C-style functions, be sure to check the return values (as mentioned in the other answers here already) - fopen for example returns a NULL pointer when it fails.

More specific to your question: Try to run your program under gdb (e.g. gdb <your-program>), to see where the Segmentation fault occurs exactly; that way you will also be able to see more details (e.g. variable contents etc.). Alternatively, if working under linux, use analysis tools such as valgrind to detect any kind of memory access problems.

Upvotes: 2

Learn to use the GDB debugger (assuming you are on Linux), or the valgrind utility. Perhaps putting your file path inside a std::string is worthwhile, and, as nyarlathotep mentioned, use a std::fstream.

It could happen that your fn is not null terminated....

Compile with g++ -Wall -g

As Anders K answered, always check the result of fopen against NULL. Pierre Vittet's Talpo extension to GCC (coded in MELT) is able to check automatically that you do check that.

Upvotes: 2

AndersK
AndersK

Reputation: 36102

you should always check return values from functions that have a return value. In this case make sure when you fopen the file that the return handle is not NULL and also make sure if you open the file, to fclose it.

Upvotes: 2

Related Questions