[Discuss] Casting the return value of malloc bad?

Adam Parkin pzelnip at telus.net
Sat Jul 15 13:48:27 PDT 2006


Andrew Resch wrote:
>> Paul Nienaber wrote:
>>> Do it this way:
>>>
>>> foo = malloc(n * sizeof(*foo));
 >>
>> Good point, but if the line immediately before the malloc looked like:
>>
>> SomeType * foo = NULL;
>>
>> then wouldn't sizeof (*foo) choke (NULL pointer dereference)?
> 
> OH sorry about the last email..  I should read before replying. 
> 
> The sizeof(*foo) will return the size of SomeType, not the length of
> data that it is pointing to.

Exactly, and that's why Paul's tip is good (so long as foo is pointing 
to a valid instance of SomeType).

I actually experienced this week in my labs as I was showing the class 
why casting the return value of malloc isn't so good.  I wrote on the board:

/* alloc memory for array of x ints */
int * p = (int *) malloc (sizeof (int) * x);	

And then said, "well what if you decide that you want an array of longs 
instead of ints, but forget to change the cast":

long * p = (int *) malloc (sizeof(int) * x);

But then of course a smart student pointed out that the code is borked 
anyways because I forgot to change the sizeof(int) to sizeof(long).  So 
then I changed it to

long * p = (int *) malloc (sizeof(long) * x);

But the odds you'll remember to change the sizeof, but not change the 
cast are pretty slim so at this point the exercise became a bit 
artificial and contrived. =8-p

I think in the end the best approach is something like:

typedef int ArrayDataType;
ArrayDataType * p = malloc (sizeof(ArrayDataType) * numElements);

Now if you decide on an array of longs instead of ints, you only need 
change the typedef line and the malloc line remains the same.

Side rant: typedef is one of the biggest things I miss going from C/C++ 
to Java, as often I want to change the type of data contained in a 
container class, but in order to do so there's usually multiple places 
where that information appears.  Usually I end up creating an artificial 
"DataElement" class which is just a wrapper for the type to be contained 
which often feels like swatting a fly with a bazooka. =8-p  Generics 
help with this, but if you have multiple containers then you still have 
multiple points where the data type appears and is still a bit of a 
maintenance problem.
-- 
--
Adam Parkin
E-mail: pzelnip at telus.net
----------------------
Every gun that is made, every warship launched, every rocket fired
signifies in the final sense, a theft from those who hunger and are not
fed, those who are cold and are not clothed.  This world in arms is not
spending money alone.  It is spending the sweat of its laborers, the
genius of its scientists, the hopes of its children.  This is not a way
of life at all in any true sense.  Under the clouds of war, it is
humanity hanging on a cross of iron.
	-- Dwight Eisenhower (April 16, 1953)


More information about the Discuss mailing list