C 分段故障(堆芯转储)和zlib

C 分段故障(堆芯转储)和zlib,c,segmentation-fault,malloc,dynamic-memory-allocation,C,Segmentation Fault,Malloc,Dynamic Memory Allocation,我对使用Linux和在C上创建任何远程严肃的东西都是非常陌生的。我一直在尝试创建一个只压缩单个字符串的程序,但在尝试运行编译后的文件时,我总是遇到这种分段错误。 我使用以下方法编译它: gcc 2.c -o test.o -lz 我的代码: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <zlib.h> #include <assert.h> i

我对使用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;
}
#包括
#包括
#包括
#包括
#包括
int main()
{
char*istream=malloc(10),*ostream=malloc(120);
istream=“istream”;
int res=压缩(ostream,(uLongf*)strlen(ostream),isttream,(ulong)strlen(isttream));
返回0;
}
有人能告诉我为什么会发生此错误,以及我如何改进代码吗?

更改:

istream = "istream"

此外,您希望strlen(ostream)返回什么?120

strlen
返回输入字符串中遇到的第一个0字符的索引

在您的情况下,
ostream
指向的内存内容是未知的(即“垃圾”)

strlen
将扫描此内存,直到遇到0字符,但可能会超过120字节的内存空间,并导致内存访问冲突


如果您有意将strlen(ostream)更改为120。

首先将
istream
指向分配的内存:

char *istream = malloc(10)
然后将其指向一个文本(因此是常量和只读)字符串:

您需要将字符串文本复制到分配的内存中,否则您将不再拥有分配的原始指针,并且内存泄漏。您也将无法
释放该指针,因为
istream
指向您尚未分配的
malloc

至于这次事故,请看大卫·赫弗南的答案



作为一个旁注,在你的代码中没有C++,只有纯的和C.< /P> < P>这条线看起来是主要的问题:

(uLongf*)strlen(ostream)
您将
大小\u t
值解释为指向缓冲区的指针。您要传递包含输出缓冲区长度的
无符号long
的地址。再看一看
compress
的文档

除此之外,您还不了解C字符串是如何工作的。赋值运算符与
char*
lvalue一起使用时,仅复制地址,而不复制字符串的内容。我建议您这样声明缓冲区:

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编译器。因此,
intmain(void)

尝试了这两种方法,sprintf(istream,“istream”)仍然会给出分段错误。好吧,假设调用
compress
时发生segfault异常,为什么不将此函数作为问题的一部分发布呢?请稍候!调用strlen(ostream)
是异常的原因。您希望它返回什么值?120?
Strern
返回输入字符串中第一次出现的0字符的索引。为什么有
C++
标记?当函数返回时,该参数将是压缩后输出的实际大小,因此它是一个“输出”参数。@JoachimPileborg它既是输入又是输出。我已经更正了我的答案。
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;
}