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

Fal*_*onD 2 c compression zlib

我编写了一个程序,该程序应该使用zlib函数compress()和uncompress()进行压缩,然后解压缩字符串,它的编译效果还不错,但是由于某种原因,当我启动它时,未压缩字符串中的一些符号丢失了-我得到的是“一些”,然后是一些系统符号。有人可以帮我在这里找到错误吗?

#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;
}
Run Code Online (Sandbox Code Playgroud)

luk*_*k32 5

检查错误代码!

luk32:gcc -lz ./zlib.c 
luk32:~/projects/tests$ ./a.out 
Buffer was too small!
Run Code Online (Sandbox Code Playgroud)

对于很小的输入,压缩通常无效。因此,您对所需缓冲区大小的预测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;
  }
}
Run Code Online (Sandbox Code Playgroud)

仔细阅读文档中的“实用程序功能”后。完整正确的代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

测试:

luk32:gcc -lz ./zlib.c 
luk32:~/projects/tests$ ./a.out 
some foo
Run Code Online (Sandbox Code Playgroud)