Thread: Gzip C++ function crashes my program.

  1. #1
    Registered User
    Join Date
    Mar 2009

    Gzip C++ function crashes my program.

    Any reason you can think of that this would crash my program:
     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);
    WHILE this works fine:
    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);

  2. #2
    Registered User
    Join Date
    Oct 2008
    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
    Registered User
    Join Date
    Dec 2007
    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, 01:49 PM
  2. <Gulp>
    By kryptkat in forum Windows Programming
    Replies: 7
    Last Post: 01-14-2006, 01:03 PM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  4. c++ linking problem for x11
    By kron in forum Linux Programming
    Replies: 1
    Last Post: 11-19-2004, 10:18 AM
  5. qt help
    By Unregistered in forum Linux Programming
    Replies: 1
    Last Post: 04-20-2002, 09:51 AM