我对使用 Linux 和在 C 上创建任何远程严肃的东西都很陌生。我一直在尝试创建一个程序来简单地压缩单个字符串,但是在尝试运行编译文件时我总是遇到这个段错误. 我编译它使用:
gcc 2.c -o test.o -lz
我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <zlib.h>
#include <assert.h>
int main ()
{
char *istream = malloc(10), *ostream = malloc(120);
istream = "istream";
int res = compress(ostream, (uLongf *)strlen(ostream), istream,(ulong)strlen(istream));
return 0;
}
谁能向我解释为什么会发生此错误以及我该如何改进我的代码?
最佳答案
这一行似乎是主要问题:
(uLongf*)strlen(ostream)
您正在将 size_t
值解释为指向缓冲区的指针。您应该传递包含输出缓冲区长度的 unsigned long
的地址。再看一下 compress
的文档。
此外,您还不了解 C 字符串的工作原理。与 char*
左值一起使用时,赋值运算符仅复制地址而不是字符串的内容。我建议您像这样声明缓冲区:
const char *istream = "istream";
char ostream[120];
我认为你的程序应该是这样的:
int main(void)
{
const char *istream = "istream";
char ostream[120];
uLongf destLen = sizeof(ostream);
int res = compress((Bytef*)ostream, &destLen, (Bytef*)istream, strlen(istream));
return 0;
}
请注意,我编写代码时假设您使用的是 C 编译器。因此 int main(void)
。
关于c - 段错误(核心转储)和 zlib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21158823/