Specifically, what's dangerous about casting the result of malloc?

Now before people start marking this a dup, I've read all the following, none of which provide the answer I'm looking for:
  1. C FAQ: What's wrong with casting malloc's return value?
  2. SO: Should I explicitly cast malloc()’s return value?
  3. SO: Needless pointer-casts in C
  4. SO: Do I cast the result of malloc?
Both the C FAQ and many answers to the above questions cite a mysterious error that castingmalloc's return value can hide, however none of them give a specific example of such an error in practice. Now pay attention that I said error, not warning.
Now given the following code:
#include <string.h>
#include <stdio.h>
// #include <stdlib.h>

int main(int argc, char** argv) {

    char * p = /*(char*)*/malloc(10);
    strcpy(p, "hello");
    printf("%s\n", p);

    return 0;
}
Compiling the above code with gcc 4.2, with and without the cast gives the same warnings, and the exec executes properly and provides the same results in both cases.
anon@anon:~/$ gcc -Wextra nostdlib_malloc.c -o nostdlib_malloc
nostdlib_malloc.c: In function main’:
nostdlib_malloc.c:7: warning: incompatible implicit declaration of built-in function malloc
anon@anon:~/$ ./nostdlib_malloc 
hello
So can anyone give a specific code example of a compile or runtime error that could occur because of casting malloc's return value, or is this just an urban legend?
Edit I've come across two well written arguments regarding this issue:
Answers:-

You won't get a compiler error, but a compiler warning. As the sources you cite say (especially thefirst one), you can get an unpredictable runtime error when using the cast without includingstdlib.h.
So the error on your side is not the cast, but forgetting to include stdlib.h. Compilers may assume that malloc is a function returning int, therefore converting the void* pointer actually returned bymalloc to int and then to your your pointer type due to the explicit cast. On some platforms, intand pointers may take up different numbers of bytes, so the type conversions may lead to data corruption.
Fortunately, modern compilers give warnings that point to your actual error. See the gcc output you supplied: It warns you that the implicit declaration (int malloc(int)) is incompatible to the built-inmalloc. So gcc seems to know malloc even without stdlib.h.
Leaving out the cast to prevent this error is mostly the same reasoning as writing
if (0 == my_var)
instead of
if (my_var == 0)
since the latter could lead to a serious bug if one would confuse = and ==, whereas the first one would lead to a compile error. I personally prefer the latter style since it better reflects my intention and I don't tend to do this mistake.
The same is true for casting the value returned by malloc: I prefer being explicit in programming and I generally double-check to include the header files for all functions I use.

0 comments:

Post a Comment

Don't Forget to comment