Gzip C++ function crashes my program.

This is a discussion on Gzip C++ function crashes my program. within the C++ Programming forums, part of the General Programming Boards category; Any reason you can think of that this would crash my program: Code: int gzdecompress(char *infilename, char *outfilename) { gzFile ...

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    76

    Gzip C++ function crashes my program.

    Any reason you can think of that this would crash my program:
    Code:
     int gzdecompress(char *infilename, char *outfilename)
     {
        gzFile infile = gzopen(infilename, "rb");
        FILE *outfile = fopen(outfilename, "wb");
        if (!infile || !outfile) easymsg("Couldn't open.");
    
       char buffer[128];
        int num_read = 0;
        while ((num_read = gzread(infile, buffer, sizeof(buffer))) > 0) {
           fwrite(buffer, 1, num_read, outfile);
          }
    
        gzclose(infile);
        fclose(outfile);
     }
    WHILE this works fine:
    Code:
    int gzCompress(char *infilename, char *outfilename)
    {
        FILE *infile = fopen(infilename, "rb");
        gzFile outfile = gzopen(outfilename, "wb");
     if (!infile || !outfile) return -1;
        char inbuffer[128];
        int num_read = 0;
        unsigned long total_read = 0, total_wrote = 0;
       while ((num_read = fread(inbuffer, 1, sizeof(inbuffer), infile)) > 0) {
           total_read += num_read;
           gzwrite(outfile, inbuffer, num_read);
        }
        fclose(infile);
        gzclose(outfile);
    
    }
    ?

  2. #2
    Registered User
    Join Date
    Oct 2008
    Posts
    1,262
    Notice that in the second example, the one that doesn't crash, you return when opening one of the files failed. That's the problem in the first example: opening the file failed. Then you try to use the file pointer anyway, which will be NULL, which will inevitably cause problems.
    Notice that if you simply return you may have a resource leak: if opening one of the two succeeds but the other one fails, you'll never close the one that succeeded.

  3. #3
    a_capitalist_story
    Join Date
    Dec 2007
    Posts
    2,648
    This is actually C code, rather than C++, by the way.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. doubt in c parser coding
    By akshara.sinha in forum C Programming
    Replies: 4
    Last Post: 12-23-2007, 12:49 PM
  2. <Gulp>
    By kryptkat in forum Windows Programming
    Replies: 7
    Last Post: 01-14-2006, 12:03 PM
  3. Replies: 3
    Last Post: 03-04-2005, 01:46 PM
  4. c++ linking problem for x11
    By kron in forum Linux Programming
    Replies: 1
    Last Post: 11-19-2004, 09:18 AM
  5. qt help
    By Unregistered in forum Linux Programming
    Replies: 1
    Last Post: 04-20-2002, 09:51 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21