LWN.net Logo

Advertisement

Advanced thin client solution for Linux, based on Open Source. Mix Windows and Linux applications on the same desktop.

Advertise here

calloc idiocy

calloc idiocy

Posted Aug 14, 2005 2:50 UTC (Sun) by giraffedata (subscriber, #1954)
In reply to: calloc idiocy by chad.netzer
Parent article: kzalloc()

I think you missed the fundamental distinction of calloc() from malloc(). The difference in how you specify the size is incidental. The reason calloc() exists is that it allocates memory that is set to zero ("c" is for "clear"), whereas malloc() allocates memory with arbitrary contents.

I'm not sure my macro example really did get garbled. It looks fine on my screen, but does look a little funny because I tried to be consistent with the earlier example that used a one-character type name. Let me try again:


  struct foo * arrayOfFooStructs;
  MALLOCARRAY(arrayOfFooStructs, 4); 

It's supposed to be two lines. The first one declares an array variable (technically a pointer, but practically an array) and the second allocates space for a 4-element array and assigns its address to that pointer. I.e. it instantiates the array.

I have seen people use special "multiply and malloc" routines in order to deal with the arithmetic overflow while not taking the time to clear the memory as with calloc(). Also, these routines sometimes multiply more than two numbers together to get the size.


(Log in to post comments)

calloc idiocy

Posted Aug 14, 2005 23:03 UTC (Sun) by chad.netzer (subscriber, #4257) [Link]

Ahh, I see. I did ignore the clearing aspect in my replies; I overlooked this as the the distinction that perhaps you (and bronson) were talking about. But I hope all this does illustrate to bronson (if he or she is reading) that calloc() requires the "nmemb" argument for a reason, and that the overflow protection is easy to overlook, but an important feature of calloc().

Ok, I understand your macro example now. A compact way of doing the array allocation without the clear, and safer than malloc(n * sizeof(struct foo)). Thanks for rewriting the declaration.

Cheers.

Copyright © 2008, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds