[Courses] [C] Lesson12: Exercise answers
Laura Bowser
lbowser at andrew.cmu.edu
Thu Nov 21 14:19:10 EST 2002
[lots of HTML junk removed]
>Is there any advantage for calloc over malloc or vice versa
[more HTML junk removed]
Slightly technical discussion follows:
calloc and malloc do *almost* the exact same thing.
the only difference is that calloc initializes the memory as well. with
malloc, your system may or may not initialize the memory. (Solaris doesn't,
Linux does)
If malloc does initialize the memory for you, there is no advantage.
if malloc does not initialize the memory for you, then there is a *very*
slight speed advantage to using malloc over calloc. This is because there is
code in calloc to initialize the memory.
if you need the memory initialized to 0 or NULL, then you're better off using
calloc because it does some memory tricks (memset) to initialize the memory
quickly (much more quickly than say a for loop).
Another issue that I used to tell my students was that calloc can be your
friend because of it's different parameter list. It helped the students
remember that you need to give calloc a number of things to allocate, and the
size of each of those things. They would tend to forget this with malloc
because it only takes one parameter.
Hope I cleared some of this up for you.
Laura
--
Public key available at
http://www.elwing.org/~elwing/lbowser.gpg
More information about the Courses
mailing list