zlib already has a simple inflate/deflate function you can use.

char a[50] = "Hello, world!";
char b[50];
char c[50];

uLong ucompSize = strlen(a)+1; // "Hello, world!" + NULL delimiter.
uLong compSize = compressBound(ucompSize);

// Deflate
compress((Bytef *)b, &compSize, (Bytef *)a, ucompSize);

// Inflate
uncompress((Bytef *)c, &ucompSize, (Bytef *)b, compSize);

When in doubt, check out the zlib manual. My code is crappy, sorry =/

Answer from Yehia Hafez on Stack Overflow
🌐
GitHub
github.com › luvit › zlib › blob › master › compress.c
zlib/compress.c at master · luvit/zlib
* For conditions of distribution ...============================================================= Compresses the source buffer into the destination buffer....
Author   luvit
🌐
Jyotiprakash's Blog
blog.jyotiprakash.org › file-compression-and-decompression-in-c-using-zlib
File compression and decompression in C using ZLib
December 31, 2023 - This C program is designed to either compress or decompress a file using the Zlib library. It takes three command-line arguments: the input file name, the operation (either "compress" or "decompress"), and the output file name.
🌐
GitHub
github.com › madler › zlib › blob › master › compress.c
zlib/compress.c at master · madler/zlib
A massively spiffy yet delicately unobtrusive compression library. - zlib/compress.c at master · madler/zlib
Author   madler
🌐
zlib
zlib.net › zlib_how.html
zlib Usage Example
February 12, 2026 - Users wonder when they should provide more input, when they should use more output, what to do with a Z_BUF_ERROR, how to make sure the process terminates properly, and so on. So for those who have read zlib.h (a few times), and would like further edification, below is an annotated example in C of simple routines to compress and decompress from an input file to an output file using deflate() and inflate() respectively.
🌐
GitHub
github.com › madler › zlib › blob › develop › compress.c
zlib/compress.c at develop · madler/zlib
A massively spiffy yet delicately unobtrusive compression library. - zlib/compress.c at develop · madler/zlib
Author   madler
🌐
GitHub
github.com › zlib-ng › zlib-ng › blob › develop › compress.c
zlib-ng/compress.c at develop · zlib-ng/zlib-ng
z_int32_t Z_EXPORT PREFIX(compress)(unsigned char *dest, z_uintmax_t *destLen, const unsigned char *source, z_uintmax_t sourceLen) {
Author   zlib-ng
🌐
Lemoda
lemoda.net › c › zlib-open-write
An example of compressing with zlib in C
September 9, 2011 - */ #define windowBits 15 #define GZIP_ENCODING 16 static void strm_init (z_stream * strm) { strm->zalloc = Z_NULL; strm->zfree = Z_NULL; strm->opaque = Z_NULL; CALL_ZLIB (deflateInit2 (strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, windowBits | GZIP_ENCODING, 8, Z_DEFAULT_STRATEGY)); } /* Example text to print out.
🌐
University of Washington
homes.cs.washington.edu › ~suciu › XMLTK › xmill › www › XMILL › html › zlib_2compress_8c.html
zlib/compress.c File Reference
Go to the source code of this file. Functions int ZEXPORT compress2 (dest, destLen, source, sourceLen, level) Bytef *dest Variables uLongf * destLen const Bytef * source uLong sourceLen int level Function Documentation · int ZEXPORT compress2 ( dest , destLen , source , sourceLen , level )
Top answer
1 of 3
32

zlib already has a simple inflate/deflate function you can use.

char a[50] = "Hello, world!";
char b[50];
char c[50];

uLong ucompSize = strlen(a)+1; // "Hello, world!" + NULL delimiter.
uLong compSize = compressBound(ucompSize);

// Deflate
compress((Bytef *)b, &compSize, (Bytef *)a, ucompSize);

// Inflate
uncompress((Bytef *)c, &ucompSize, (Bytef *)b, compSize);

When in doubt, check out the zlib manual. My code is crappy, sorry =/

2 of 3
8

You can't printf the deflated output like this. It's not null terminated. You can't strlen it either.

Since your input is a string though you probably do want to only pass the content of the string including the null terminator. So set avail_in to strlen(a) + 1.

You need to examine the next_out and avail_out fields after you call deflate to see how much data was written to the output buffer.

See documentation here under the deflate call.

Here's your modified code. Note if you're compressing something that is not a string you'll need to change this and also with strings you may compress without the terminating zero and add it back after decompressing.

char a[50] = "Hello World!";
char b[50];
char c[50];

// deflate
// zlib struct
z_stream defstream;
defstream.zalloc = Z_NULL;
defstream.zfree = Z_NULL;
defstream.opaque = Z_NULL;
defstream.avail_in = (uInt)strlen(a)+1; // size of input, string + terminator
defstream.next_in = (Bytef *)a; // input char array
defstream.avail_out = (uInt)sizeof(b); // size of output
defstream.next_out = (Bytef *)b; // output char array

deflateInit(&defstream, Z_DEFAULT_COMPRESSION);
deflate(&defstream, Z_FINISH);
deflateEnd(&defstream);

// This is one way of getting the size of the output
printf("Deflated size is: %lu\n", (char*)defstream.next_out - b);

// inflate
// zlib struct
z_stream infstream;
infstream.zalloc = Z_NULL;
infstream.zfree = Z_NULL;
infstream.opaque = Z_NULL;
infstream.avail_in = (uInt)((char*)defstream.next_out - b); // size of input
infstream.next_in = (Bytef *)b; // input char array
infstream.avail_out = (uInt)sizeof(c); // size of output
infstream.next_out = (Bytef *)c; // output char array

inflateInit(&infstream);
inflate(&infstream, Z_NO_FLUSH);
inflateEnd(&infstream);

printf("Inflate:\n%lu\n%s\n", strlen(c), c);
Find elsewhere
🌐
GitHub
github.com › madler › zlib › blob › master › test › example.c
zlib/test/example.c at master · madler/zlib
February 17, 2020 - A massively spiffy yet delicately unobtrusive compression library. - zlib/test/example.c at master · madler/zlib
Author   madler
Top answer
1 of 5
53

zlib.h has all the functions you need: compress (or compress2) and uncompress. See the source code of zlib for an answer.

CopyZEXTERN int ZEXPORT compress OF((Bytef *dest,   uLongf *destLen, const Bytef *source, uLong sourceLen));
/*
         Compresses the source buffer into the destination buffer.  sourceLen is
     the byte length of the source buffer.  Upon entry, destLen is the total size
     of the destination buffer, which must be at least the value returned by
     compressBound(sourceLen).  Upon exit, destLen is the actual size of the
     compressed buffer.

         compress returns Z_OK if success, Z_MEM_ERROR if there was not
     enough memory, Z_BUF_ERROR if there was not enough room in the output
     buffer.
*/

ZEXTERN int ZEXPORT uncompress OF((Bytef *dest,   uLongf *destLen, const Bytef *source, uLong sourceLen));
/*
         Decompresses the source buffer into the destination buffer.  sourceLen is
     the byte length of the source buffer.  Upon entry, destLen is the total size
     of the destination buffer, which must be large enough to hold the entire
     uncompressed data.  (The size of the uncompressed data must have been saved
     previously by the compressor and transmitted to the decompressor by some
     mechanism outside the scope of this compression library.) Upon exit, destLen
     is the actual size of the uncompressed buffer.

         uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
     enough memory, Z_BUF_ERROR if there was not enough room in the output
     buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.  In
     the case where there is not enough room, uncompress() will fill the output
     buffer with the uncompressed data up to that point.
*/
2 of 5
39

This is an example to pack a buffer with zlib and save the compressed contents in a vector.

Copyvoid compress_memory(void *in_data, size_t in_data_size, std::vector<uint8_t> &out_data)
{
 std::vector<uint8_t> buffer;

 const size_t BUFSIZE = 128 * 1024;
 uint8_t temp_buffer[BUFSIZE];

 z_stream strm;
 strm.zalloc = 0;
 strm.zfree = 0;
 strm.next_in = reinterpret_cast<uint8_t *>(in_data);
 strm.avail_in = in_data_size;
 strm.next_out = temp_buffer;
 strm.avail_out = BUFSIZE;

 deflateInit(&strm, Z_BEST_COMPRESSION);

 while (strm.avail_in != 0)
 {
  int res = deflate(&strm, Z_NO_FLUSH);
  assert(res == Z_OK);
  if (strm.avail_out == 0)
  {
   buffer.insert(buffer.end(), temp_buffer, temp_buffer + BUFSIZE);
   strm.next_out = temp_buffer;
   strm.avail_out = BUFSIZE;
  }
 }

 int deflate_res = Z_OK;
 while (deflate_res == Z_OK)
 {
  if (strm.avail_out == 0)
  {
   buffer.insert(buffer.end(), temp_buffer, temp_buffer + BUFSIZE);
   strm.next_out = temp_buffer;
   strm.avail_out = BUFSIZE;
  }
  deflate_res = deflate(&strm, Z_FINISH);
 }

 assert(deflate_res == Z_STREAM_END);
 buffer.insert(buffer.end(), temp_buffer, temp_buffer + BUFSIZE - strm.avail_out);
 deflateEnd(&strm);

 out_data.swap(buffer);
}
🌐
Hackage
hackage.haskell.org › package › zlib
zlib: Compression and decompression in the gzip and zlib formats
zlib-0.7.1.1.tar.gz [browse] (Cabal source package) ... This package provides a pure interface for compressing and decompressing streams of data represented as lazy ByteStrings. It uses the zlib C library so it has high performance.
🌐
FileFormat
products.fileformat.com › compression › zlib
Open Source C Library for Compression & Decompression of Data Files
April 9, 2026 - zlib – An open source free C data compression library to create archiver that enables computer programmers to compress and decompress your data and data.
🌐
zlib
zlib.net
zlib Home Site
The zlib data format is itself portable across platforms. Unlike the LZW compression method used in Unix compress(1) and in the GIF image format, the compression method currently used in zlib essentially never expands the data. (LZW can double or triple the file size in extreme cases.) zlib's ...
🌐
NCBI
ncbi.nlm.nih.gov › IEB › ToolBox › CPP_DOC › lxr › source › include › util › compress › zlib › zlib.h
/c++/include/util/compress/zlib/zlib.h
NCBI Home IEB Home C++ Toolkit docs C Toolkit source browser · Source navigation Diff markup Identifier search General search · /* zlib.h -- interface of the 'zlib' general purpose compression library version 1.2.12, March 11th, 2022 Copyright (C) 1995-2022 Jean-loup Gailly and Mark Adler ...
🌐
IT trip
en.ittrip.xyz › c language
Developing Data Compression Utilities in C with the zlib Library | IT trip
December 26, 2024 - By the end of this guide, you’ll have a solid foundation to create efficient, reliable, and maintainable compression utilities in C. ... zlib is a widely-used open-source library for data compression, offering fast and efficient functionality.
🌐
University of Washington
homes.cs.washington.edu › ~suciu › XMLTK › xmill › www › XMILL › html › example_8c-source.html
example.c Source File
/* just read the zlib header */ 00392 00393 err = inflateInit(&d_stream); 00394 CHECK_ERR(err, "inflateInit"); 00395 00396 d_stream.next_out = uncompr; 00397 d_stream.avail_out = (uInt)uncomprLen; 00398 00399 inflate(&d_stream, Z_NO_FLUSH); 00400 CHECK_ERR(err, "inflate"); 00401 00402 d_stream.avail_in = (uInt)comprLen-2; /* read all compressed data */ 00403 err = inflateSync(&d_stream); /* but skip the damaged part */ 00404 CHECK_ERR(err, "inflateSync"); 00405 00406 err = inflate(&d_stream, Z_FINISH); 00407 ·
🌐
GitHub
github.com › PowerShell › ZLib › blob › master › compress.c
ZLib/compress.c at master · PowerShell/ZLib
/* compress.c -- compress a memory buffer · * Copyright (C) 1995-2005, 2014, 2016 Jean-loup Gailly, Mark Adler · * For conditions of distribution and use, see copyright notice in zlib.h · */ · /* @(#) $Id$ */ · #define ZLIB_INTERNAL · #include "zlib.h" ·
Author   PowerShell
🌐
Stack Abuse
stackabuse.com › python-zlib-library-tutorial
Python zlib Library Tutorial
July 17, 2023 - The Python zlib library provides a Python interface to the zlib C library, which is a higher-level abstraction for the DEFLATE lossless compression algorithm....