我刚刚遇到了一种很奇怪的行为。如果我只使用压缩函数,那么一切都可以正常工作,但是如果我试着去做的话。将压缩数据保存到文件中,我得到了Z_BUF_ERROR。我做错了什么?
#include <iostream>
#include <fstream>
#include "zlib.h"
typedef unsigned char byte_t;
static int read_filesize(const char* filename) {
int size = -1;
std::ifstream file(filename);
if (!file.is_open()) return size;
file.seekg(0, std::ios::end);
size = (int) file.tellg();
file.close();
return size;
}
static bool read_binary_file(const char* filename, byte_t* dst, const unsigned length) {
std::ifstream file(filename, std::ios::binary);
if (!file.is_open()) return false;
file.read((char*) dst, length);
file.close();
return true;
}
static bool save_binary_file(const char* filename, const byte_t* src, const unsigned length) {
std::ofstream file(filename, std::ios::binary);
if (!file.is_open()) return false;
file.write((const char*) src, length);
file.close();
return true;
}
int main(int args, char **argv) {
int fileSize = read_filesize(argv[1]);
byte_t fileData[fileSize];
bool result = read_binary_file(argv[1], fileData, fileSize);
unsigned compressedSize = compressBound(fileSize);
byte_t compressed[compressedSize];
int compressionResult = compress(compressed, (unsigned long*) &compressedSize, fileData, fileSize);
switch (compressionResult) {
case Z_OK:
std::cout << "Compression succeeded!\n";
break;
case Z_MEM_ERROR:
std::cout << "Error: Z_MEM_ERROR!\n";
return 1;
case Z_BUF_ERROR:
std::cout << "Error: Z_BUF_ERROR!\n";
return 1;
default:
std::cout << "Error: UNDEFINED!\n";
return 1;
}
std::cout << "Size of '" << argv[1] << "': " << fileSize << "\n"
<< "After: " << compressedSize << "\n";
bool saveResult = save_binary_file("file.bin.z", compressed, compressedSize); // everything works if I remove this instruction
return 0;
}发布于 2013-11-04 16:41:35
从上面的注释中可以看出,您使用的是64位架构,其中使用的是sizeof(unsigned long)==8,而不是sizeof(unsigned)==4。
因此,强制转换(unsigned long*)&compressedSize ( compressedSize是unsigned类型)会产生未定义的行为。
只要将compressedSize的声明更改为unsigned long类型,就可以解决这个问题。
发布于 2013-11-01 12:50:34
堆栈溢出?我不知道动态数组是如何在g++中实现的,但是如果将它们放到堆栈中,那么大文件可能会有问题。使用std::vector或std::array。
发布于 2013-11-04 11:40:40
int fileSize = read_filesize(argv[1]);
byte_t fileData[fileSize];它是VLA (可变长度数组)。不得使用。使用std::向量代替。同样的情况适用于compressed
https://stackoverflow.com/questions/19725318
复制相似问题