Monday 31 October 2016

c - Casting allocated memory through double pointer

It is a good idea to cast the void pointer returned by malloc to the type of the destination pointer. In this case you can find an error similar to the error in your code snippet.




char **ptr;
ptr=(char *)malloc(sizeof(char)*value);


Here variable ptr has type char ** while the right side of the assignment statement has type char * due to the casting. So the compiler shall issue an error (more precisely a diagnostic message) because there is no implicit conversion from char *. to char **



By the way by this reason in C++ there is not allowed to assign a pointer of type void * to pointers of other types because such a code is unsafe.



The other reason to cast the void pointer returned by malloc is to make your code self-documented. Consider for example the following statement




p = malloc( sizeof( *p ) );


Here it is difficult to understand what is the type of memory is allocated. It would be much better to write for example



p = ( double * )malloc( sizeof( *p ) );


In this case the statement is more clear and you need not to scroll a big program listing that to determine what is the type of p.




Take into account that a good program is a program where each statement provides you as much information as you need that to understand what the statement is trying to do and what types of variables envolved in expressions..



There is one more reason to cast the pointer returned by malloc. If you will try to compile your code with a C++ compiler then it will issue numerous errors for each using of malloc without casting. When you will transfer your code from C to C++ you will estimate the value of such casting.



Here is the correct using of malloc for your example



char **ptr;

ptr = ( char ** )malloc( value * sizeof( char * ) );

for ( i = 0; i < value; i++ )
ptr[i] = ( char * )malloc( another_value * sizeof( char ) );

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...