Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

casting

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.

like image 246
Naftaly Avatar asked Mar 27 '13 22:03

Naftaly


People also ask

Should I cast the return value of malloc?

In C, you don't need to cast the return value of malloc . The pointer to void returned by malloc is automagically converted to the correct type. However, if you want your code to compile with a C++ compiler, a cast is needed.

What happens if you don't cast malloc?

It is ok if you don't cast, but please don't discourage others doing that. malloc() returns void* . In C, you can do this: int *p = malloc(sizeof(int)); . In C++, however, you have to explicitly cast the return like int *p = (int*)malloc(sizeof(int)); to prevent a compiling error.

Why we use typecasting in malloc?

Casting the result of malloc() to the appropriate pointer type enables the compiler to catch subsequent inadvertent pointer conversions. When allocating individual objects, the "appropriate pointer type" is a pointer to the type argument in the sizeof expression passed to malloc() .


2 Answers

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.

like image 173
Timo Geusch Avatar answered Oct 26 '22 07:10

Timo Geusch


The second line is wrong (casting to a char will truncate the pointer to just one byte, making the data tmpString contains an invalid address), but all casts in C are unchecked so you'll never get an error over them.

like image 26
Rafe Kettler Avatar answered Oct 26 '22 06:10

Rafe Kettler