使用zlib压缩/解压缩char数组,缺少一些字符

时间:2014-01-17 12:53:24

标签: c compression zlib

我编写了一个程序,据说应该使用zlib函数compress()和uncompress()压缩然后解压缩字符串,它编译得很好,但出于某种原因,当我启动它时,一些符号来自未压缩的字符串丢失 - 我得到的是“some”,然后是一些系统符号。谁能帮助我在这里找到错误?

#include "string.h"
#include "stdio.h"
#include "stdlib.h"
#include "zlib.h"
int main()
{
const char *istream = "some foo";
ulong destLen = strlen(istream);
char* ostream = malloc(2 * strlen(istream));
int res = compress(ostream, &destLen, istream, destLen + 1);


const char *i2stream = ostream;
char* o2stream = malloc(4 * strlen(istream));
ulong destLen2 = strlen(i2stream);
int des = uncompress(o2stream, &destLen2, i2stream, destLen2);
printf("%s", o2stream);
return 0;
}

1 个答案:

答案 0 :(得分:5)

检查错误代码!!

luk32:gcc -lz ./zlib.c 
luk32:~/projects/tests$ ./a.out 
Buffer was too small!

对于非常小的输入,压缩通常是无效的。因此,您对所需缓冲区大小2*strlen(istream)的预测低估了。

"改进" zlib.c检查出现了什么问题:

#include "string.h"
#include "stdio.h"
#include "stdlib.h"
#include "zlib.h"
int main()
{
  const char *istream = "some foo";
  ulong destLen = strlen(istream);
  char* ostream = malloc(2 * strlen(istream));
  int res = compress(ostream, &destLen, istream, destLen + 1);
  if(res == Z_BUF_ERROR){
    printf("Buffer was too small!\n");
    return 1;
  }
  if(res ==  Z_MEM_ERROR){
    printf("Not enough memory for compression!\n");
    return 2;
  }
}

仔细阅读文档中的"Utility Functions"。完整正确的代码:

#include "string.h"
#include "stdio.h"
#include "stdlib.h"
#include "zlib.h"
int main()
{
  const char *istream = "some foo";
  ulong srcLen = strlen(istream)+1;      // +1 for the trailing `\0`
  ulong destLen = compressBound(srcLen); // this is how you should estimate size 
                                         // needed for the buffer
  char* ostream = malloc(destLen);
  int res = compress(ostream, &destLen, istream, srcLen); 
  // destLen is now the size of actuall buffer needed for compression
  // you don't want to uncompress whole buffer later, just the used part
  if(res == Z_BUF_ERROR){
    printf("Buffer was too small!\n");
    return 1;
  }
  if(res ==  Z_MEM_ERROR){
    printf("Not enough memory for compression!\n");
    return 2;
  }

  const char *i2stream = ostream;
  char* o2stream = malloc(srcLen);
  ulong destLen2 = destLen; //destLen is the actual size of the compressed buffer
  int des = uncompress(o2stream, &srcLen, i2stream, destLen2);
  printf("%s\n", o2stream);
  return 0;
}

测试:

luk32:gcc -lz ./zlib.c 
luk32:~/projects/tests$ ./a.out 
some foo