Casting result of malloc to char (not char*) - why doesn't compiler complain?

c, casting

Solution

The first line casts the (void) pointer that malloc returns into a pointer to char, thus preserving both its pointeredness. All it is telling the compiler is that "the memory at location X should be viewed as a character array".

The second cast turns the pointer returned by malloc into a single character. That's bad for multiple reasons:

- You lose the pointer as you've just turned the pointer into something completely different

- You're also losing the majority of the numerical value of the pointer because the size of the character is much less than the size of the pointer (in a lot of cases, the pointer is 32 or 64 bit in size but the character only 8 bit) and the "superfluous" bits get discarded.

I would think that a compiler with the warning level cranked up sufficiently high should warn about the second assignment.

Problem

``` tmpString = (char*)malloc((strlen(name) + 1) * sizeof(char)); tmpString = (char )malloc((strlen(name) + 1) * sizeof(char)); ``` What is the difference between these 2 lines? My understanding is that the second line is wrong but from some reason the compiler says nothing.

Original source