使用compress时出现缓冲区错误

时间:2015-04-21 20:54:15

标签: c linux zlib

在跟随here的示例后,我似乎失败了。

#define CHECK_ERR(retcode, msg) { \                                             
  if (retcode != Z_OK) { \                                                      
    fprintf(stderr, "%s on using %s\r\n", zError(retcode), msg); \              
    exit(1); \                                                                  
  } \                                                                           
}

int main(int argc, char* argv[]) { 
  Bytef a[1000];                                                                
  Bytef b[1000];                                                                
  Bytef c[1000];                                                                
  uLongf compressed_size;                                                       
  uLongf uncompressed_size;                                                     
  int retcode;                                                                  
  size_t i;                                                                     

  uncompressed_size = 800;                                                      
  for (i = 0; i < uncompressed_size; i++) {                                     
    a[i] = ((uint8_t)i) & 255;                                                  
  }                                                                             

  retcode = compress(b, &compressed_size, a, uncompressed_size);                
  CHECK_ERR(retcode, "compress");                                               
  retcode = uncompress(c, &uncompressed_size, b, compressed_size);              
  CHECK_ERR(retcode, "uncompress"); 
}

我收到缓冲区错误:Z_BUF_ERROR( - 5)

程序返回:

buffer error on using compress

2 个答案:

答案 0 :(得分:0)

我没有错误。我不得不在顶部添加:

#include <stdio.h>
#include <stdlib.h>
#include "zlib.h"

答案 1 :(得分:-1)

我已编辑了您的问题,添加了必需的内容。 值得一提的是,-lz也应该给予链接器。 我确实检查过你这个代码确实出错了。
但是替换

  Bytef a[100];
  Bytef b[100];                                                                
  Bytef c[100];

  Bytef *a = calloc(100, sizeof(Bytef));
  Bytef *b = calloc(100, sizeof(Bytef));
  Bytef *c = calloc(100, sizeof(Bytef));
  if (NULL == a || NULL == b || NULL == c) exit(1);      

并添加调试

  for (i = 0; i < uncompressed_size; i++) {
    a[i] = ((uint8_t)i) & 255;
    printf("%d ", a[i]);
  }
  printf("\n");
  retcode = compress(b, &compressed_size,(const Bytef*) a, uncompressed_size);
  CHECK_ERR(retcode, "compress");
  for (i = 0; i < compressed_size; i++) {
    printf("%d ", b[i]);
  }
  printf("\n");
  retcode = uncompress(c, &uncompressed_size, b, compressed_size);
  CHECK_ERR(retcode, "uncompress");
  for (i = 0; i < uncompressed_size; i++) {
    printf("%d ", c[i]);
  }

产生正确:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 
120 156 99 96 100 98 102 97 101 99 231 224 228 226 230 225 229 227 23 16 20 18 6 0 5 70 0 191 
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19