You are not logged in.

#1 2009-03-10 23:41:34

big_gie
Member
Registered: 2005-01-19
Posts: 637

[Solved] File opened in function leak???

Hi,

I'm writting a library in C++. I'm not using anything advanced in C++: its mostly similar to C.

This library is being called by a C program, which was compiled using g++, thus as a C++ program.

Everything works fine, except today I've stumble into a weird bug. It seems the library is leaking file handles. In one of the library routine, I open a file, write data in it, and close it, like this:

library_functiop() {
    FILE *fh_out_sp = NULL;
    fh_out_sp = fopen("logfile.log","a");
    if ( fh_out_sp == NULL )
    {
        fprintf(stderr, "ERROR: Can't open file logfile.log\n");
        getchar();
        abort();
    }
[...code...]
    fprintf(fh_out_sp,...);
[...code...]
    int closing = fclose(fh_out_sp);
    if (closing != 0 || closing == EOF)
    {
        fprintf(stderr, "ERROR: Can't CLOSE file output/latest/singlephoton.log\n");
        getchar();
        abort();
    }
}

The code then calls that function. But after a while (this is called thousands of times), the log file can't be opened anymore, I get:

ERROR: Can't open file output/latest/singlephoton.log

While the function is stuck at the getchar() call, I can "lsof -p `pidof myprogram`". What I saw was strange: the program had around a thousand of opened logfile.log!!!

[...]
myprogram 21854 me 1023w   REG    8,7     4121 22086039 /full/path/to/logfile.log
[...]

What can be wrong??? How come the file is not closed correctly?? I test when I open the file, I even test when I close the file...

Thanx a lot for your help!!!

Last edited by big_gie (2009-03-11 02:54:56)

Offline

#2 2009-03-11 02:54:38

big_gie
Member
Registered: 2005-01-19
Posts: 637

Re: [Solved] File opened in function leak???

Damnit. A coworker inserted a return statement before the file was closed, hence the file stayed open after each call!

Refactoring corrected the problem.

Offline

Board footer

Powered by FluxBB