Should I use free() in Subfunction after malloc()?

Viewed 93

In my project have a sub-function. In this function, I need to store my data temporarily. So I use malloc(), I'm not sure whether is necessary to use free()?

void *hash2(unsigned char *mes, element_t d)
{
    size_t iterations = strlen(mes) / 8;
    unsigned char *rtemp = malloc(32 * sizeof(char));
    SHA256(mes, iterations, rtemp);
    element_from_hash(d, rtemp, 32);
    free(rtemp);
}
2 Answers

Yes, as you are not using the allocated memory anymore, you must free it.

Once you return from the function call, you'll have no way to access the allocated memory, hence it cannot be freed up. So, you need to to pass the pointer to free() before leaving the function scope (as seen in the snippet) to avoid memory leak.

As already stated in the present answer, you should free any memory that is no longer needed, if you allocate memory within the function, not freeing it and not returning any pointer to it will cause a memory leak.

Note that your function *hash2(...), having void* return type, must return a value, if you don't need it to, use void instead.

In your particular code it does seem that you wouldn't need to use malloc anyway, you can use a local array unsigned char rtemp[32];. malloc is a heavy function that involves system calls, if you can avoid it, you should.

Related