Question

I am very new to both using Linux and creating anything remotely serious on C. I've been trying to create a program which will simply compress a single string, but I keep getting this Segmentation fault when trying to run the compiled file. I compiled it using:

gcc 2.c -o test.o -lz

My code:

#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;
}

Could anyone explain to me why this error is happening and how can I improve my code?

Was it helpful?

Solution

This line would appear to be the main problem:

(uLongf*)strlen(ostream)

You are interpreting a size_t value as a pointer to a buffer. You are meant to pass the address of an unsigned long containing the length of the output buffer. Take another look at the documentation for compress.

On top of that you don't yet understand how C strings work. The assignment operator when used with a char* lvalue merely copies an address and not the contents of a string. I suggest that you declare your buffers like this:

const char *istream = "istream";
char ostream[120];

I think your program should be something along these lines:

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;
}

Note that I wrote the code assuming that you are using a C compiler. And hence int main(void).

OTHER TIPS

First you make istream point to memory you allocate:

char *istream = malloc(10)

then you make it point to a literal (and therefore constant and read-only) string:

istream = "istream";

You need to copy the string literal into the allocated memory, or you will no longer have the original pointer you allocated and have a memory leak. You also will not be able to free that pointer, since istream points to something you haven't allocated with malloc.

As for the crash, see the answer by David Heffernan.


As a side-note, there is no C++ in your code, only pure and plain C.

Change:

istream = "istream"

To

strcpy(istream,"istream");

In addition, what did you expect strlen(ostream) to return? 120?

strlen returns the index of the first 0 character encountered within the input string.

In your case, the contents of the memory pointed by ostream is unknown (i.e. "junk").

strlen will scan this memory until a 0 character is encountered, but will probably exceed the 120-byte memory space and cause a memory access violation.

Change strlen(ostream) to 120 if that was your intention.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top