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.
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.
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.
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() .
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:
I would think that a compiler with the warning level cranked up sufficiently high should warn about the second assignment.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With