0

I have a function defined in a library that I reference with -lcrypto for gcc This is the definition from the header file

unsigned char *SHA256(const unsigned char *d, size_t n, unsigned char *md);

The definition https://github.com/openssl/openssl/blob/master/crypto/sha/sha256.c#L63

The function takes a char pointer as the third argument, fills it with results, and returns it.

If I passed a NULL as that third parameter, the function creates a pointer and ignores it, then returns it.

I know that in order to return a pointer it must be allocated on the heap, thus a malloc must have been called.

But when I call this function

unsigned char * hash = SHA256((char*) &bh, sizeof(struct DIGEST), NULL);

I expect hash to be a pointer to a memory address so I run free(hash) and then it fails.

free(): invalid pointer: 0x00007f301f7958a0 ***
Aborted (core dumped)

Which of assumptions are wrong?

doc_id
  • 1,363
  • 13
  • 41
  • 1
    If you look at the code, the returned value is a static variable in the function itself. You must not free it. You also must not use it after another call to the routine. – stark Mar 18 '18 at 17:12
  • 1
    As you can see from lines 68 and 69 of the [file you referenced](https://github.com/openssl/openssl/blob/master/crypto/sha/sha256.c#L63), if you pass in a NULL pointer, it does *not* in fact allocate a pointer with `malloc`; rather, it sets up a pointer to internal static memory, which is fine, but it means that you do not need to, and must not, try to free it. So your wrong assumption was that the code called `malloc`. – Steve Summit Mar 18 '18 at 17:12
  • can any of you post that in an answer so to accept? – doc_id Mar 18 '18 at 18:13
  • https://www.openssl.org/docs/man1.0.2/crypto/sha.html (yes, openssl documentation generally is horrible, but in this case it's mostly clear) – Matteo Italia Mar 19 '18 at 00:05

0 Answers0