473,385 Members | 1,740 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Difference?

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.
Nov 14 '05 #1
15 2210
Mohanasundaram wrote:
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:ro**@nunnisoft.ch
http://www.nunnisoft.ch
Residenza Boschetto 12 tel/fax: +41-91-6046511
6935 Bosco Luganese """ mobile: +41-76-3208561
Switzerland (o o)
========================oOO==(_)==OOo============= ===========

Nov 14 '05 #2
Mohanasundaram wrote:

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.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!

Nov 14 '05 #3
CBFalconer <cb********@yahoo.com> wrote in message news:<40**************@yahoo.com>...
Mohanasundaram wrote:

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.


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... ;)

--
Peter
Nov 14 '05 #4
CBFalconer <cb********@yahoo.com> wrote in message news:<40**************@yahoo.com>...
Mohanasundaram wrote:

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.


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.
Nov 14 '05 #5
mo************@msn.com (Mohanasundaram) writes:
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).
--
"Large amounts of money tend to quench any scruples I might be having."
-- Stephan Wilms
Nov 14 '05 #6
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.

On Mon, 23 Feb 2004, Ben Pfaff wrote:
mo************@msn.com (Mohanasundaram) writes:
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).
--
"Large amounts of money tend to quench any scruples I might be having."
-- Stephan Wilms

Nov 14 '05 #7

"Mohanasundaram" <mo************@msn.com> wrote
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

Nov 14 '05 #8
mo************@msn.com (Mohanasundaram) wrote:
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?


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

Result of malloc is required to be aligned for all uses. Result of calloc,
as far as I remeber, does not have such requirement.

Jacob
Nov 14 '05 #9
nrk
Yakov Lerner wrote:
mo************@msn.com (Mohanasundaram) wrote:
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?
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.
Jacob


--
Remove devnull for email
Nov 14 '05 #10
On 23 Feb 2004 19:39:53 -0800, in comp.lang.c , ai***@acay.com.au (Peter
Nilsson) wrote:
CBFalconer <cb********@yahoo.com> wrote in message news:<40**************@yahoo.com>...
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

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.

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.com/ms3/bchambless0/welcome_to_clc.html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 14 '05 #11
On 23 Feb 2004 22:59:48 -0800, in comp.lang.c , mo************@msn.com
(Mohanasundaram) wrote:

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));
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.com/ms3/bchambless0/welcome_to_clc.html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 14 '05 #12
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.
Nov 14 '05 #13
mo************@msn.com (Mohanasundaram) writes:
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.
Nov 14 '05 #14

In article <87************@pfaff.stanford.edu>, Ben Pfaff <bl*@cs.stanford.edu> writes:
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 mi************@microfocus.com

"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_
Nov 14 '05 #15
On 24 Feb 2004 21:19:07 -0800, in comp.lang.c , mo************@msn.com
(Mohanasundaram) wrote:
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....

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.com/ms3/bchambless0/welcome_to_clc.html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 14 '05 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

34
by: yensao | last post by:
Hi, I have a hard time to understand difference and similarities between Relational database model and the Object-Oriented model. Can somebody help me with this? Thank you in advance. ...
21
by: b83503104 | last post by:
Hi, Can someone tell me the difference between single quote and double quote? Thanks
26
by: Frank | last post by:
For my website i would like to display the age of my son in years, months, days and hours. For now i manage to get a result for totals. Like the total number of days. This is the beginning: ...
21
by: Rich | last post by:
I was considering C# for developing a scientific application, but I have noticed a ~30% difference between VC++ .NET and C# on the same machine, under identical conditions: double a = 0,b = 0, c...
4
by: jamesyreid | last post by:
Hi, I'm really sorry to post this as I know it must have been asked countless times before, but I can't find an answer anywhere. Does anyone have a snippet of JavaScript code I could borrow...
3
by: bbawa1 | last post by:
Hi, I have a table which has a field ItemsReceived of type datetime. I have a grid view which has two columns. In first column i have to show the data from field ItemsReceived and in second...
12
by: Petronius | last post by:
Hallo, does anyone have an idea how to implement difference lists in Javascript? Thanks allot in advance
5
by: Julius | last post by:
Hej dudes, I need to calc the difference between two timestamps / dates ... For example what i need to calculate: Date 1: 2007.11.06 - 20:13:04 Date 2: 2007.11.07 - 21:13:04 Difference:...
9
by: viki1967 | last post by:
Hi all! This new forum its great! :) Congratulations !!! My answer: why this my code not working? Nothing error but not work the difference.... : <html>
11
by: cmb3587 | last post by:
I have two arrays and I'm trying to create a 3rd array that is the difference between the two arrays Ex: arrayA: 3 5 8 9 arrayB: 3 4 6 9 difference of A-B: 5 8 however, my...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.