简体   繁体   中英

C crypt function, malloc and valgrind

My man page for the crypt function states that:

"The return value points to static data whose content is overwritten by each call."

However, when using the SHA512 version (ie, the salt starts $6$...), valgrind does not seem to agree. Unless I free the pointer that crypt returns, it gets upset:

120 bytes in 1 blocks are still reachable in loss record 1 of 1
at 0x4C2BBA0: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
by 0x4C2DF4F: realloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
by 0x521F4D4: __sha512_crypt (sha512-crypt.c:437)

Conversely, valgrind is fine if I use the DES version (so salt does not start with $6$ or similar).

What's going on here and is this behaviour explained anywhere?

Thanks in advance.

EDIT: Platform is Ubuntu 15.04 64-bit. Here's a program:

#define _XOPEN_SOURCE 700
#include <unistd.h>

int main(int argc, char** argv) {
    char *hash = crypt("password", "$6$Salty");
    return 0;
}

For some crypt variations, the preallocated buffer is not big enough, so it allocates (via malloc) a buffer that will be reused by the next call to crypt that needs a large buffer (possibly after realloc ing it). That's why it is noted as "still reachable" by valgrind -- there's a static variable in the library that points at the block.

If you were to free it, it's likely the next call to crypt would misbehave (likely giving a runtime error about reusing a freed block).

No matter how many times you call crypt there will be one block identified by valgrind like this. It isn't a real memory leak, just constant overhead from the library that is pretty much impossible to avoid.

Generally you want to ignore valgrind messages about "still reachable" blocks unless the amount of memory is unexpectedly large, or the requests are coming from a place that should not be storing the returned pointers in global variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM