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

tmpString = (char*)malloc((strlen(name) + 1) * sizeof(char));
tmpString = (char )malloc((strlen(name) + 1) * sizeof(char));

What is the difference between these two lines?

I understand that the second line is incorrect, but for some reason the compiler is not saying anything.

+5
source share
4 answers

The first line indicates the pointer (void), which malloc returns to a pointer to char, thereby preserving it as its pointer. All this tells the compiler that "memory at location X should be treated as an array of characters."

The second throw turns the pointer returned by malloc into one character. This is bad for several reasons:

  • You are losing the pointer because you just turned the pointer into something completely different.
  • , ( 32 64 , 8 ), "" .

, , , .

+5

( char , tmpString ), C , .

+2

, undefined. , , , . , . - , .

+2

, tmpString char *, , , :

6.5.16.1

< >

1 : 112) - , , ,

- , , .

- , ( , lvalue) , - , ;

- , ( , lvalue), , - void, , , , ;

- , , - ;

- , _Bool, - .

- ?

0

All Articles