Malloc
Wiki
< All Topics
Print

Malloc

How to correctly use malloc

This one is tricky. Let me start with one correct possibility.

    int* val = (int*) malloc(sizeof(int));
    if(!val){
        //handle the error
    }

It is tricky because of the seemingly unnecessary casting. Why should we use it?
Well, we may not use cast. Even experts do not have a definitive answer. See this excerpt from Effective C, by Robert Seacord (2020):

"Even expert C programmers disagree about whether to cast the pointer
returned by malloc to a pointer to the type of the declared object …
Strictly speaking, this cast is unnecessary. C will allow you to implicitly convert a pointer to void to a pointer … Casting the result of malloc to the intended pointer type enables the compiler to catch inadvertent pointer conversions, as well as differences between the size of the allocation and the size …".

In summary, the casting's only purpose is to hint to the compiler about what we want to do, so the compiler can warn us if we commit some strange errors, such as using malloc to allocate memory of a different size from the pointer.

Another possible approach is to use the variable itself in the sizeof operator. I have mixed feelings about this approach and personally never use it. However, I have seen some codes that employ this approach. If you spot anything terribly wrong with this construction, please let me know in the comments.

    int* val = malloc(sizeof(*val));
    if(!val){
        //handle the error
    }

This approach has the advantage of being safer if we change the type of the variable val, for instance, from int to double (we will not have to change anything in the sizeof of the malloc). Nevertheless, many experts will argue that the code may be less legible if you use this approach.

For an interesting (and nerdy) discussion about the correct use of the malloc, check the SEI CERT C guideline https://wiki.sei.cmu.edu/confluence/display/c/MEM02-C.+Immediately+cast+the+result+of+a+memory+allocation+function+call+into+a+pointer+to+the+allocated+type.

References

Seacord, R. C. Secure Coding in C and C++. Reino Unido: Pearson Education. 2013.

https://wiki.sei.cmu.edu/confluence/display/c/MEM02-C.+Immediately+cast+the+result+of+a+memory+allocation+function+call+into+a+pointer+to+the+allocated+type

Seacord, R. C. Effective C: An Introduction to Professional C Programming. No Starch Press. 2020.

Sumário