Reputation: 1779
I have a main that do:
unsigned char *f_hmac = calculate_hmac(output_file_path, mac_key, keyLength);
fwrite(f_hmac, 1, 64, fpout);
free(f_hmac);
and a function (which prototype is:unsigned char *calculate_hmac(const char *filename, const unsigned char *key, size_t keylen)
) that do:
unsigned char *hmac = malloc(64);
hmac = gcry_md_read(hd, GCRY_MD_SHA512);
return hmac;
My problem is that when the main do free(f_hmac)
i got:
*** glibc detected *** ./polcrypt: free(): invalid pointer: 0x00000000023a8ad8 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x7eb96)[0x7f0fd662db96]
./polcrypt[0x40220f]
./polcrypt[0x401851]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xed)[0x7f0fd65d076d]
./polcrypt[0x4015e9]
and i don't understand why.
OS: GNU/Linux Ubuntu 12.10
GCC 4.7.2/Clang 3.2
cflags -Wall -Wextra -D_FORTIFY_SOURCE=2 -O2 -Wformat -Wformat-security -fstack-protector-all -fmudflap -fPIE
Upvotes: 0
Views: 147
Reputation: 179392
From the docs:
The returned message digest is allocated within the message context and therefore valid until the conext [sic] is released.
So, you need to make sure to release the message context, but you don't need to allocate or free hmac
.
If you will release the message context before returning from calculate_hmac
, you need to copy the hmac out:
unsigned char *hmac = malloc(64);
unsigned char *m_hmac = gcry_md_read(gd, GCRY_MD_SHA512);
memcpy(hmac, m_hmac, 64);
return hmac;
Upvotes: 3
Reputation: 16718
You're allocating hmac
, then overwriting your newly allocated pointer with the result of gcry_md_read
:
unsigned char *hmac = malloc(64);
hmac = gcry_md_read(hd, GCRY_MD_SHA512);
The documentation of gcry_md_read states that:
gcry_md_read returns the message digest after finalizing the calculation. This function may be used as often as required but it will alwas return the same value for one handle. The returned message digest is allocated within the message context and therefore valid until the conext is released.
So unless you want to keep the pointer around after the context is released, you don't need to malloc or free anything:
unsigned char *hmac = gcry_md_read(hd, GCRY_MD_SHA512);
Upvotes: 2