curl / Mailing Lists / curl-library / Single Mail


Re: Memory Leak detected by Valgrind

From: Michael König via curl-library <>
Date: Fri, 7 Dec 2018 14:42:55 +0100 (CET)

> Sileno de Oliveira Brito via curl-library <> hat am 6. Dezember 2018 um 14:40 geschrieben:
> How to solve the memory leak question when use the libcurl?
> in my main i have in line 33 the call
OpenSSL is one of the culprits, which does not do proper cleanup at the programs end. Their attitude has been, that they run until the very end of the programs life, why free everything if the whole heap is disposed of anyway?

While this is true for the purpose of the program itself, it screws over everyone who uses a library like that and intends to use a tool like valgrind or VLD or something like that.

We ran into this issue 10 years ago and i went and looked if there was something i could do to get OpenSSL to do a cleaner, if not absolutely pristine, cleanup.

This is what i came up with:

#include <openssl/conf.h>
#include <openssl/engine.h>
#include <openssl/crypto.h>
#include <openssl/ssl.h>
#include <openssl/err.h>

/* -----------------------------------------------------------------------------------------------------------------------------
 * @Function: CleanupSSLLibrary
 * @Info : Does all known cleanup for the OpenSSL library to get its memory freed. OpenSSL itself doesnt seem to have any
 * severe memory leaks, but it doesnt seem to have any global shutdown routine that frees all reserved memory either.
 * So we try our best here to free as much as possible. Once the program is terminated it doesnt matter anyway. The
 * output of automated leak detection utilities however will report unfreed memory blocks because of this.
 * ----------------------------------------------------------------------------------------------------------------------------- */
void CleanupSSLLibrary(void)
  int i, iNumOfLocks = CRYPTO_num_locks();

  if (l_pLockHandlesSSL != NULL){

    for (i=0; i < iNumOfLocks; i++) CloseHandle(l_pLockHandlesSSL[i]);

    l_pLockHandlesSSL = NULL;


  /* global application exit cleanup (after all SSL activity is shutdown) */

The includes may not be in the necessary order. This is Windows code, you will need another include for "Closehandle" or an equivalent method.

The 1st part deals with freeing the multithreading locks you need for crashless multithreaded operation with OpenSSL. If you did not allocate them you do not need clean them up. Also if you did not allocate them, do not use OpenSSL in a multithreaded fashion!

The 5 calls below should free all but 2 memory buffers that OpenSSL allocates. IIRC ERR_free_strings() needs to be called in each thread that used the error handling of OpenSSL.

Maybe this helps someone, maybe OpenSSL got its act together in the past decade. I do not think it will hurt presenting this here.

  Michael König

Received on 2018-12-07