gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:40:39 25 4
gpt4 key购买 nike

我写了一个程序,据说应该使用 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;
}

最佳答案

检查错误代码!!

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

关于使用 zlib 压缩/解压缩字符数组,缺少一些字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21186535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com