[Libcgi-general] Re: Memory allocation problems in md5 function
Brought to you by:
rafaelsteil
From: Rafael S. <ra...@in...> - 2003-05-15 12:52:39
|
Hello, sorry for the long delay to anwser. You're right, the function is completely buggy. I'll fix according your comments and put the fixed version in the CVS. Thanks, Rafael ------------------ Hi, I am currently using version 0.8.2 and I think I've found a memory allocation problem in the md5 function. Output of valgrind indicated so. There's one line in the function which allocates memory for the output variable: tmp = (char *)malloc(str_size); If the input is less than 32 characters, then str_size will be less than 33, which causes problems. MD5 produces 128 bit hashes, which is equal to 16 bytes. Since the output string contains 2 bytes for each byte of the hash, then we need 32 bytes. Add the terminating null character, and the required number of bytes is 33. Therefore the above code should read: tmp = (char *) malloc(33); The other problem is at the for loop, which is run for 32 times. Since MD5 produces 16 bytes of output, then we only need to run the loop for 16 times only. Therefore, the for loop should read: for(i = 0; i < 16; i++){ snprintf(buf, sizeof(float), "%02x", md[i]); strncat(tmp, buf, sizeof(float)); } Consequently, the following line is also incorrect: tmp[i] = '\0'; This will truncate the output to 16 characters, thus it should be changed to: tmp[32] = '\0'; |