查找openssl内存泄漏(代码)

#include <stdio.h>
#include <string.h>
#include <openssl/bio.h>
#include <openssl/crypto.h>

static BIO *bio_err = NULL;

void mem_debug_start()
{
    bio_err = BIO_new(BIO_s_file());
    if (!bio_err) {
        printf("mem_debug_start bio_err ERRPR!\n");
        return;
    }   

    BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);
    CRYPTO_malloc_debug_init();
    CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
    CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
}

void mem_debug_stop()
{
    if (bio_err) {
        CRYPTO_mem_leaks(bio_err);
        BIO_free(bio_err);
    }   
}

int main(void)
{
    char *p = NULL, *num = "123";

    mem_debug_start();
    
    p = OPENSSL_malloc(4);

    memmove(p, num, strlen(num));

    printf("%s\n", p); 

//     OPENSSL_free(p);
//     p = NULL;

    mem_debug_stop();

    return 0;
}

编译:
gcc mem_debug.c -I . -I ~/openssl/soft/include -lssl -lcrypto -L ~/openssl/soft/lib -ldl

  运行后会出现错误提示:

123
[16:17:47]     0 file=mem_debug.c, line=36, thread=3077924488, number=4, address=09DA3150

  因为p没有释放所有存在内存泄漏。在ssl编程一书中的第五章内存分配对此进行了讲解。

  openssl中提供了一些强大的内存管理函数,可以方便的检查内存泄漏点,可以看出一次对内存的申请造成了多大的内存泄漏,是那个文件,那句造成的。

猜你喜欢

转载自www.cnblogs.com/coolYuan/p/8963972.html
今日推荐