Hi All,

The following C++ function, which utilizes libz compression library, generates a segfault error and aborts execution when decompressedStream->write((char*)out, have) line is executed on Ubuntu 64-bit platform:

Code:
static const int CHUNK = 16384;

int decompressData(unsigned char* compressedData, int len, stringstream* decompressedStream, int compressionFormat)
{
    int ret;
    int have;
    z_stream strm;
    unsigned char out[CHUNK];

    /* allocate inflate state */
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;
    strm.avail_in = 0;
    strm.next_in = Z_NULL;

    if(compressionFormat)//gzip
    {
        ret = inflateInit2(&strm, 16+MAX_WBITS);
    }
    else//deflate
    {
        ret = inflateInit(&strm);
    }

    if (ret != Z_OK)
        return ret;

    /* decompress until deflate stream ends or end of file */
    do {
        strm.avail_in = len;

        if (strm.avail_in == 0)
            break;

        strm.next_in = compressedData;

        /* run inflate() on input until output buffer not full */
        do {
            strm.avail_out = CHUNK;
            strm.next_out = out;
            ret = inflate(&strm, Z_NO_FLUSH);
            assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
            switch (ret) {
            case Z_NEED_DICT:
                ret = Z_DATA_ERROR;     /* and fall through */
            case Z_DATA_ERROR:
            case Z_MEM_ERROR:
                (void)inflateEnd(&strm);
                return ret;
            }
            have = CHUNK - strm.avail_out;

            decompressedStream->write((char*)out, have);  <<<==== This line crashes !
        } while (strm.avail_out == 0);

        /* done when inflate() says it's done */
    } while (ret != Z_STREAM_END);

    (void)inflateEnd(&strm);

    return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
}
As you can see, CHUNK has the value of 16384. Hence, the buffer pointed by 'out' has the size 16384.

On the line decompressedStream->write((char*)out, have), I suspect that, this error is specific to 64-bit, and an invalid memory write probably takes place since there is a mismatch between the value of 'have' variable, which is 14376 at the time of the crash, and the size of the buffer pointed by 'out'.

However, I could not figure out what reason causes this error.

Any ideas will be appreciated.

Thanks.