Joona I Palaste wrote:
> ytrama wrote:
>
>>I have read in one old posting that
>>[you shouldn't] cast [the] pointer which is returned by malloc.
>>I would like to know the reason.
>
> It won't fix anything
> but it may make the compiler think problems are fixed
> when they really aren't.
>
> Longer explanation:
> Without a proper prototype for malloc(),
> the compiler thinks it returns int.
> Thus, when malloc creates a void* value and returns it,
> the compiler implicitly converts it to int.
> The value is *already* broken at this case,
> so no amount of casting it to anything will help.
> However, if you cast it to a pointer type,
> the compiler will *think* you know what you're doing and omit a warning.
> Thus you get broken code that looks like working code.
That's *not* true.
> cat f.c
void f(void) {
char* p = (char*)malloc(12

;
for (size_t j = 0; j < 128; ++j)
p[j] = j;
}
> gcc -Wall -std=c99 -pedantic -c f.c
f.c: In function `f':
f.c:2: warning: implicit declaration of function `malloc'
f.c:3: error: `size_t' undeclared (first use in this function)
f.c:3: error: (Each undeclared identifier is reported only once
f.c:3: error: for each function it appears in.)
f.c:3: error: parse error before "j"
f.c:3: error: `j' undeclared (first use in this function)
f.c:3: error: parse error before ')' token
f.c: At top level:
f.c:2: warning: unused variable `p'
The compiler gives ample diagnostics
should you fail to #include <stdlib.h>
which defines malloc(size_t) and size_t.
On good reason for casting malloc(int) to the desired type
is so you can compile with a C++ compiler:
> cat f.cc
#include <stdlib.h>
void f(void) {
char* p = malloc(12

;
for (size_t j = 0; j < 128; ++j)
p[j] = j;
}
> g++ -Wall -ansi -pedantic -c f.cc
f.cc: In function `void f()':
f.cc:4: error: invalid conversion from `void*' to `char*'