Reputation: 689
I am trying to compress image data using zlib's compress()
function. For this purpose I allocate memory equal to compressBound()
of input data to the output buffer. But I keep getting the Z_BUF_ERROR
. Why is it happening ?
for (y = 0; y < header.cupsHeight; y ++)
{
pixdata = malloc(header.cupsBytesPerLine);
if(pixdata==NULL)
{
fprintf(stderr,"error in memory allocation for pixdata\n");
return -1;
}
cupsRasterReadPixels(ras, pixdata, header.cupsBytesPerLine);
destLen = compressBound(header.cupsBytesPerLine);
fprintf(stderr, "mem. dest. = %lld\n",destLen);
write_buffer = malloc(destLen);
if(write_buffer==NULL)
{
fprintf(stderr,"error in memory allocation for write_buffer\n");
return -1;
}
ret = compress(write_buffer, &destLen, pixdata, header.cupsBytesPerLine);
if (ret != Z_OK)
zerr(ret);
fwrite(write_buffer, 1, destLen, stdout);
free(write_buffer);
free(pixdata);
}
Error checking of value returned is performed by this function:
/* report a zlib or i/o error */
void zerr(int ret)
{
fputs("zpipe: ", stderr);
switch (ret) {
case Z_ERRNO:
fputs("error in source data or output file\n", stderr);
break;
case Z_STREAM_ERROR:
fputs("invalid compression level\n", stderr);
break;
case Z_DATA_ERROR:
fputs("invalid or incomplete deflate data\n", stderr);
break;
case Z_MEM_ERROR:
fputs("out of memory\n", stderr);
break;
case Z_VERSION_ERROR:
fputs("zlib version mismatch!\n", stderr);
break;
case Z_BUF_ERROR:
fputs("error in buffer\n",stderr);
break;
}
}
When I run the program each time the compress()
function is called, I get zpipe: error in buffer
(the last case in zerr()
function). Also memory allocation does not fail as I have included the condition for it and it evaluates to false each time the loop is called.
Upvotes: 0
Views: 541
Reputation: 70362
You ask for the memory bound for compressing some number of bytes:
destLen = compressBound(header.cupsBytesPerLine);
But, then you attempt to compress 1 more byte than what you had computed the bound for.
ret = compress(write_buffer, &destLen, pixdata, header.cupsBytesPerLine+1);
Upvotes: 1