Difference?

M

Mohanasundaram

Hi All,

What is the difference between malloc and calloc other than the
point that calloc will initialize the memory to all zeros? This was an
interview question for me. All the books and references that I have
come across tells that calloc initialize the memory to all zeros. In
Herbert Shiltd's C/C++ reference I found that calloc returns a pointer
to an array. I want to understand in what way the memory returned by
malloc and calloc are different?

Regards,
Mohan.
 
R

Roberto Nunnari

Mohanasundaram said:
Hi All,

What is the difference between malloc and calloc other than the
point that calloc will initialize the memory to all zeros? This was an
interview question for me. All the books and references that I have
come across tells that calloc initialize the memory to all zeros. In
Herbert Shiltd's C/C++ reference I found that calloc returns a pointer
to an array. I want to understand in what way the memory returned by
malloc and calloc are different?

Regards,
Mohan.

AFAIK there are only two differences:
- the signature
- calloc zeros the returned memory area (as you noted above)

Best regards.
--
Roberto Nunnari -software engineer-
mailto:[email protected]
http://www.nunnisoft.ch
Residenza Boschetto 12 tel/fax: +41-91-6046511
6935 Bosco Luganese """ mobile: +41-76-3208561
Switzerland (o o)
========================oOO==(_)==OOo========================
 
C

CBFalconer

Mohanasundaram said:
What is the difference between malloc and calloc other than the
point that calloc will initialize the memory to all zeros? This
was an interview question for me. All the books and references
that I have come across tells that calloc initialize the memory
to all zeros. In Herbert Shiltd's C/C++ reference I found that
calloc returns a pointer to an array. I want to understand in
what way the memory returned by malloc and calloc are different?

This illustrates why all books by Schildt should be burned on
sight. They both return a void*, i.e. a pointer to void, which
can be trivially coerced into any type of pointer. This is very
definitely NOT an array. The calling sequence is different, and
callocs bit zeroed memory is not necessarily zeroes. Especially
it is not necessarily so if used for pointers and/or floats. This
makes it useful in practice only for bytes (chars) and integers.
 
P

Peter Nilsson

CBFalconer said:
This illustrates why all books by Schildt should be burned on
sight.

How do you get that illustration from the above post's token mention
of what Schildt says?!! And _all books_ by Schildt?! AFAIK, they
aren't all on C.
They both return a void*, i.e. a pointer to void, which
can be trivially coerced into any type of pointer. This is very
definitely NOT an array.

7.20.3.1 The calloc function

Synopsis
1 #include <stdlib.h>
void *calloc(size_t nmemb, size_t size);

Description
2 The calloc function allocates space for an array of nmemb objects,
each of whose size is size. The space is initialized to all bits
zero.252)

Returns
3 The calloc function returns either a null pointer or a pointer to
the allocated space.

Okay, so it returns a pointer to allocated space for an array, not an
array.

I don't think that distinction _alone_ calls for book burning... ;)
 
M

Mohanasundaram

CBFalconer said:
This illustrates why all books by Schildt should be burned on
sight. They both return a void*, i.e. a pointer to void, which
can be trivially coerced into any type of pointer. This is very
definitely NOT an array. The calling sequence is different, and
callocs bit zeroed memory is not necessarily zeroes. Especially
it is not necessarily so if used for pointers and/or floats. This
makes it useful in practice only for bytes (chars) and integers.

Hi,

After posting this question I did some search and read somewhere that
malloc is used for allocating memory for an object and calloc for
allocating memory for an array of objects. The internal difference is
that malloc will align the memory assuming that the memory allocated
is for a single object and calloc will align the memory assuming that
it is an array of objects. I think it makes more sense because why
should there exists two calls both returning pointers to memory
allocated which can be used in similar way with no other big
difference.
Somebody please throw more light on this.

Regards,
Mohan.
 
B

Ben Pfaff

After posting this question I did some search and read somewhere that
malloc is used for allocating memory for an object and calloc for
allocating memory for an array of objects. The internal difference is
that malloc will align the memory assuming that the memory allocated
is for a single object and calloc will align the memory assuming that
it is an array of objects. I think it makes more sense because why
should there exists two calls both returning pointers to memory
allocated which can be used in similar way with no other big
difference.

Although I've seen similar claims, they're all false. The memory
allocated by malloc() is properly aligned for any object or array
of objects. Here is what the standard says:

The order and contiguity of storage allocated by successive
calls to the calloc, malloc, and realloc functions is
unspecified. The pointer returned if the allocation succeeds
is suitably aligned so that it may be assigned to a pointer
to any type of object and then used to access such an object
or an array of such objects in the space allocated (until
the space is explicitly deallocated).
 
S

Stephen S M WONG

Well, as I understand, calloc will clear (set to binary
zero) the memory segment allocated for you, but malloc
won't. So, they are implemented in different ways, although
similar in most actual usages.

My 2 cents.

Stephen Wong @ Hong Kong.
 
T

Tommy

Mohanasundaram said:
After posting this question I did some search and read somewhere that
malloc is used for allocating memory for an object and calloc for
allocating memory for an array of objects. The internal difference is
that malloc will align the memory assuming that the memory allocated
is for a single object and calloc will align the memory assuming that
it is an array of objects. I think it makes more sense because why
should there exists two calls both returning pointers to memory
allocated which can be used in similar way with no other big
difference.
Somebody please throw more light on this.

This is all very interesting but "alignment" in my opinion makes more sense
when talking about structures than malloc/calloc..... Malloc and calloc
allocate contiguous memory, so.....
Also, my compiler, for example, implements calloc by calling malloc and then
setting everything to 0, nothing else involved really.

Tommy
 
N

nrk

Yakov said:
Besides memory zeroing difference, calloc and malloc have different
alignment requirements for what they return. This is subtle difference.

No. Perhaps there are implementations that use stricter alignment
requirements for calloc than they do for malloc, but again, there's nothing
in the standard that mandates this behavior. C99:

7.20.3 Memory management functions

1 The order and contiguity of storage allocated by successive calls to the
calloc, malloc, and realloc functions is unspecified. The pointer returned
if the allocation succeeds is suitably aligned so that it may be assigned
to a pointer to any type of object and then used to access such an object
or an array of such objects in the space allocated (until the space is
explicitly deallocated).

Note that this applies to all 3 allocation functions: calloc, malloc and
realloc. The alignment requirements on all 3 are the same.
Result of malloc is required to be aligned for all uses. Result of calloc,
as far as I remeber, does not have such requirement.
See above.

-nrk.
 
M

Mark McIntyre

7.20.3.1 The calloc function snip
Description
2 The calloc function allocates space for an array of nmemb objects, snip
Returns
3 The calloc function returns either a null pointer or a pointer to
the allocated space.

note that it doesn't say "callog returns an array" it says that it
allocates enough space for one, then returns a void pointer to it.
Okay, so it returns a pointer to allocated space for an array, not an
array.

you noticed...
I don't think that distinction _alone_ calls for book burning... ;)

It does, if it says that a difference between calloc and malloc is that one
returns an array, and the other returns a pointer.
 
M

Mark McIntyre

After posting this question I did some search and read somewhere that
malloc is used for allocating memory for an object and calloc for
allocating memory for an array of objects.

It might be that this is how some people use it, but its not a difference
in how they function. Both allocate memory, but calloc zeros it out.
There's no other difference.
The internal difference is
that malloc will align the memory assuming that the memory allocated
is for a single object and calloc will align the memory assuming that
it is an array of objects.

AFAIK this isn't correct. These code snippets are equivalent and both
create a pointer to an array of 10 doubles, set to all-bits-zero.

double *x= malloc(10*sizeof (double));
memset(x, 0, 10 * sizeof(double));
and
double*x = calloc(10, sizeof(double));
 
M

Mohanasundaram

Hi All,

After reading all the postings in this thread I have a query in
my mind. If there is no big difference between malloc and calloc then
why there exists two functions for memory allocation which can be
achieved by one sigle function like

struct x
{
int a;
char b;
};

calloc(1,sizeof(struct x)); for allocating one object
calloc(2,sizeof(struct x)); for allocating array of objects

or

malloc(sizeof(struct x)*1); for allocating one object
malloc(sizeof(struct x)*2); for allocating array of objects

I am ignoring the "zeroing the bits" feature of calloc as it is a
small difference as the primary discussion I guess is the memory
allocation part of those functions.

Regards,
Mohan.
 
B

Ben Pfaff

After reading all the postings in this thread I have a query in
my mind. If there is no big difference between malloc and calloc then
why there exists two functions for memory allocation which can be
achieved by one sigle function like

Historical reasons. It's always been that way, so that's the way
it is. Also, historically all-bits-zero made up the null pointer
and floating point zero values (this is still true on many
systems), making calloc() more useful.
 
M

Michael Wojcik

Historical reasons. It's always been that way, so that's the way
it is. Also, historically all-bits-zero made up the null pointer
and floating point zero values (this is still true on many
systems), making calloc() more useful.

And there was no structure copy, which made memset() after malloc()
more common, which in turn made calloc() more useful.

These days, I find it's generally most convenient to reset newly-
allocated structures using structure copy:

/* A complete definition of struct x is in scope... */
static const struct x x0;

struct x x0 = {0}, *xs;
xs = malloc(sizeof *xs);
if (xs)
*xs = x0;

.... and so forth. {0} is guaranteed to initialize pointers and
floating-point values correctly (except in the case of unions),
so structure copy will initialize the newly-allocated structure
to a predictable state.


--
Michael Wojcik (e-mail address removed)

"Well, we're not getting a girl," said Marilla, as if poisoning wells were
a purely feminine accomplishment and not to be dreaded in the case of a boy.
-- L. M. Montgomery, _Anne of Green Gables_
 
M

Mark McIntyre

Hi All,

After reading all the postings in this thread I have a query in
my mind. If there is no big difference between malloc and calloc then
why there exists two functions for memory allocation which can be
achieved by one sigle function

Since zeroing out memory is often a Good Thing:
malloc might be considered fast-but-dirty.
calloc might be considered slow-but-safe.

This is a simplification, and of course you can achieve calloc with a
malloc/memset pair. but we assume that the compiler writer has access to
some optimised way of doing calloc which is more efficient than
malloc/memset, and since memory operations are often heavily used in C,
optimised ways to do them are a Good Thing too.

By the way, you could use the same logic for putc & puts, scanf & sscanf,
and probably quite a few other C features - including integer
multiplication....
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top