I was wondering what is the difference between the two lines.
char *ptr;
ptr = malloc(10);
and this one.
char *ptr;
ptr = (char *) malloc(10);
Are you like casting the memory returned by malloc?
I was wondering what is the difference between the two lines.
char *ptr;
ptr = malloc(10);
and this one.
char *ptr;
ptr = (char *) malloc(10);
Are you like casting the memory returned by malloc?
Yes, in the second example you are casting the return value. However, you should not do that!
For detailed information go to this link: Do I cast the result of malloc?
In fact they are equivalent but the second one is preferable. moreover the first record will not be compiled in C++. So even taking in account this reason it is better to use the second record. Take the best from C++.
Why is the second record preverable. For example can you say what type of memory there is allocated in the following statement
p = malloc( 10 * sizeof( *p ) );
This statement says nothing to the reader of the code what type of memory is allocated and he has to list the listing to find the definition of p that to say what type of memory is allocated. But even if he will find the definition of variable p he will not be sure that this statement with malloc is correct because he does not know what is the actual type of expression
malloc( 10 * sizeof( *p ) );
As the expression has type void * then it can be assigned to a pointer of any type. This is a source of some kind of errors.
For example it may be that the intention of the author of the code was to allocate an array of characters
( char * )malloc( 10 * sizeof( *p ) );
but you can not say this if you will see only
malloc( 10 * sizeof( *p ) );
But are you sure that there is indeed allocated an array of characters? Maybe the author of the code meant
( char ( * )[2] )malloc( 10 * sizeof( *p ) );
or even
( char ( * )[5] )malloc( 10 * sizeof( *p ) );
or even
( short * )malloc( 10 * sizeof( *p ) );
and so on.
Every code snippet should have as much information that it was clear without any comments what the code snippet is written for.
When the compilers were not so smart as now then they did not report whether the function malloc was defined in the code that is whether the corresponding header was included. In this case by default the compiler considered the function as having the return type int. And if you did not use the casting then the compiler could report an error. But now there is no any sense in such a trick. The compilers report if a function was not declared. Try do the all that the code will be more readable and clear.