473,700 Members | 2,579 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

difference between malloc and calloc?

hai to everybody,
i am having doubt in difference between the malloc
and calloc function.
please tell where to use and when to use those functions?

Nov 19 '05 #1
8 11176
venkatesh <pv***********@ gmail.com> schrieb:
hai to everybody,
i am having doubt in difference between the malloc
and calloc function.
please tell where to use and when to use those functions?


malloc takes one parameter (number of chars to allocate) and
does not initialize the allocated memory, whereas calloc takes
two parameters (number of elements and number of chars per
element) and initialises the allocated memory to zero.

Examples:

// This allocats 500 ints, it does not initialize the memory:
int *m = malloc(500*size of(int));

// This, too, allocates 500 ints, but initializes the memory
// to zero:
int *c = calloc(500,size of(int));

hth.

Markus
Nov 19 '05 #2
venkatesh wrote:
hai to everybody,
i am having doubt in difference between the malloc
and calloc function.
please tell where to use and when to use those functions?


Markus Becker has explained the difference. The second
part of your question is about which function to use under
what circumstances, and my suggestion is "Use malloc() almost
always and calloc() almost never."

The reason is that the initialization to zero that calloc()
performs is usually not very helpful:

- The initialization to "all-bits-zero" is not necessarily
the same as initialization to "all-data-zero." C says
very little about the representation of values in memory,
nothing at all for floating-point or pointer values. On
many machines all-bits-zero representations will in fact
correspond to f.p. zeroes or null pointers, but this is
not guaranteed by the language and there have been machines
where the correspondence did not hold. If you get in the
habit of using calloc() to initialize f.p. and pointer
items, you may be heading for trouble.

- Usually, one allocates a chunk of dynamic memory in order
to store something in it -- and when you store something
in it, you'll overwrite whatever was there before. Thus,
the initialization performed by calloc() is usually not
needed anyhow. There are occasional exceptions where all-
bits-zero initialization is helpful, but they are unusual.
Not unheard-of, I grant, but unusual.

There's one possible advantage I can imagine for calloc() over
malloc(), and that's the opportunity for a tiny bit of sanity-
checking. Here are two ways you might try to allocate memory to
hold N items of SomeType:

SomeType *p = malloc(N * sizeof *p);
SomeType *q = calloc(N, sizeof *q);

Now, if N is so large that multiplying it by sizeof(SomeType )
exceeds the valid range of size_t, the argument in the first
form will "wrap around" and you'll silently request less memory
than you wanted; if the request succeeds you'll proceed merrily
along and try to store N items in too small a space, with the
usually unhappy and sometimes baffling consequences. The second
form, however, will fail and return NULL so your program will be
alerted that the space was not available; there'll be no silent
error. However, this seems to me to be a very small advantage,
so I'll stick with my original suggestion: malloc() almost always,
calloc() almost never.

--
Eric Sosman
es*****@acm-dot-org.invalid

Nov 19 '05 #3
Eric Sosman wrote:
There's one possible advantage I can imagine for calloc() over
malloc(), and that's the opportunity for a tiny bit of sanity-
checking. Here are two ways you might try to allocate memory to
hold N items of SomeType:

SomeType *p = malloc(N * sizeof *p);
SomeType *q = calloc(N, sizeof *q);

Now, if N is so large that multiplying it by sizeof(SomeType )
exceeds the valid range of size_t, the argument in the first
form will "wrap around" and you'll silently request less memory
than you wanted; if the request succeeds you'll proceed merrily
along and try to store N items in too small a space, with the
usually unhappy and sometimes baffling consequences. The second
form, however, will fail and return NULL so your program will be
alerted that the space was not available; there'll be no silent
error. However, this seems to me to be a very small advantage,
so I'll stick with my original suggestion: malloc() almost always,
calloc() almost never.


Does this mean that

void *my_calloc1(siz e_t a, size_t b)
{
void *p = malloc(a * b);
if(p) memset(p, 0, a * b);
return p;
}

would not be a valid implementation of calloc, because of the
possibility of overflow?

If calloc needs to check for overflow in a * b, how should it do so?

void *my_calloc2(siz e_t a, size_t b)
{
void *p = NULL;
size_t n = a * b;
if(a && b && n / a == b && n / b == a)
{
p = malloc(n);
if(p) memset(p, 0, n);
}
return p;
}

Perhaps this is overkill...

--
Simon.
Nov 19 '05 #4
Simon Biber wrote:

Eric Sosman wrote:
There's one possible advantage I can imagine for calloc() over
malloc(), and that's the opportunity for a tiny bit of sanity-
checking. Here are two ways you might try to allocate memory to
hold N items of SomeType:

SomeType *p = malloc(N * sizeof *p);
SomeType *q = calloc(N, sizeof *q);

Now, if N is so large that multiplying it by sizeof(SomeType )
exceeds the valid range of size_t, the argument in the first
form will "wrap around" and you'll silently request less memory
than you wanted; if the request succeeds you'll proceed merrily
along and try to store N items in too small a space, with the
usually unhappy and sometimes baffling consequences. The second
form, however, will fail and return NULL so your program will be
alerted that the space was not available; there'll be no silent
error. However, this seems to me to be a very small advantage,
so I'll stick with my original suggestion: malloc() almost always,
calloc() almost never.
Does this mean that

void *my_calloc1(siz e_t a, size_t b)
{
void *p = malloc(a * b);
if(p) memset(p, 0, a * b);
return p;
}

would not be a valid implementation of calloc, because of the
possibility of overflow?


I don't know.
If calloc needs to check for overflow in a * b, how should it do so?

void *my_calloc2(siz e_t a, size_t b)
{
void *p = NULL;
size_t n = a * b;
if(a && b && n / a == b && n / b == a)
{
p = malloc(n);
if(p) memset(p, 0, n);
}
return p;
}

Perhaps this is overkill...


I think calloc(0) should return the same value as malloc(0),
whatever that may be.

And I think that only one of these checks is needed:
n / a == b && n / b == a

void *my_calloc3(siz e_t a, size_t b)
{
void *p;
size_t n;

if (a == 0 || b == 0) {
p = malloc(0);
} else {
n = a * b;
if (n / a == b) {
p = malloc(n);
if (p != NULL) {
memset(p, 0, n);
}
} else {
p = NULL;
}
}
return p;
}

--
pete
Nov 20 '05 #5
Simon Biber wrote:
Eric Sosman wrote:
There's one possible advantage I can imagine for calloc() over
malloc(), and that's the opportunity for a tiny bit of sanity-
checking. Here are two ways you might try to allocate memory to
hold N items of SomeType:

SomeType *p = malloc(N * sizeof *p);
SomeType *q = calloc(N, sizeof *q);

Now, if N is so large that multiplying it by sizeof(SomeType )
exceeds the valid range of size_t, the argument in the first
form will "wrap around" and you'll silently request less memory
than you wanted; if the request succeeds you'll proceed merrily
along and try to store N items in too small a space, with the
usually unhappy and sometimes baffling consequences. The second
form, however, will fail and return NULL so your program will be
alerted that the space was not available; there'll be no silent
error. However, this seems to me to be a very small advantage,
so I'll stick with my original suggestion: malloc() almost always,
calloc() almost never.

Does this mean that

void *my_calloc1(siz e_t a, size_t b)
{
void *p = malloc(a * b);
if(p) memset(p, 0, a * b);
return p;
}

would not be a valid implementation of calloc, because of the
possibility of overflow?


Yes, I think it would be invalid. The Standard says (in
7.20.3.1)

The calloc function allocates space for an array of
/nmemb/ objects, each of whose size is /size/. [...]

This is subject to the general condition in 7.20.3

[...] If the space cannot be allocated, a null pointer
is returned. [...]

Thus, if calloc() cannot find sufficient space for /nmemb/
objects of /size/ bytes each, it must return NULL. There is no
special dispensation for overflow of nmemb * size; there is just
the requirement for a NULL returned value.
If calloc needs to check for overflow in a * b, how should it do so?


The response by "pete" seems to cover what's needed.

--
Eric Sosman
es*****@acm-dot-org.invalid
Nov 20 '05 #6
pete wrote:

void *my_calloc3(siz e_t a, size_t b)
{
void *p;
size_t n;

if (a == 0 || b == 0) {
p = malloc(0);
} else {
n = a * b;
if (n / a == b) {
To be pedantic, size_t may theoretically promote to int, which can
overflow.

if (a <= ((size_t) -1) / b) {
n = a * b;
p = malloc(n);
if (p != NULL) {
memset(p, 0, n);
}
} else {
p = NULL;
}
}
return p;
}


--
Peter

Nov 20 '05 #7
On 2005-11-20, Peter Nilsson <ai***@acay.com .au> wrote:
pete wrote:

void *my_calloc3(siz e_t a, size_t b)
{
void *p;
size_t n;

if (a == 0 || b == 0) {
p = malloc(0);
} else {
n = a * b;
if (n / a == b) {


To be pedantic, size_t may theoretically promote to int, which can
overflow.


Eh? If size_t can promote to int, how can it overflow it?
Nov 20 '05 #8
Jordan Abel wrote:

On 2005-11-20, Peter Nilsson <ai***@acay.com .au> wrote:
pete wrote:

void *my_calloc3(siz e_t a, size_t b)
{
void *p;
size_t n;

if (a == 0 || b == 0) {
p = malloc(0);
} else {
n = a * b;
if (n / a == b) {


To be pedantic, size_t may theoretically promote to int, which can
overflow.


Eh? If size_t can promote to int, how can it overflow it?


I suppose if 'a' was lower ranking than int,
like unsigned short or unsigned char,
and the max value for that type was equal to INT_MAX,
and 'a' was equal to INT_MAX and 'b' was greater than 1,
or any other combination where the product of a*b exceded INT_MAX,
then a*b would overflow.

If a byte has enough bits to represent all the positive
values within the range of int,
then an allowable way to implement an int,
is to make sizeof(int) equal to 2,
and use the high order byte just for the sign bit.

I never heard of a size_t lower ranking than unsigned.
It would be strange, but I think it's allowed.

--
pete
Nov 20 '05 #9

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

Similar topics

17
4882
by: rihad | last post by:
To make up a proper dynamically allocated empty C string, would it suffice to say: return calloc(1, 1); or am I better off using the longer version char *p = malloc(1); if (p) *p = 0; return p;
14
6508
by: Rahul Gandhi | last post by:
Which one is more fast? malloc followed by memset or calloc
27
4755
by: MK | last post by:
I am a newbie. Please help. The following warning is issued by gcc-3.2.2 compiler (pc Linux): ================================================================== read_raw_data.c:51: warning: assignment makes pointer from integer without a cast ================================================================== when the following piece of code was compiled. The offending statement is calloc. A similar statement in the main() function...
15
2236
by: Mohanasundaram | last post by:
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...
37
2569
by: Harsimran | last post by:
Can any one explain what are far pointers and what is the difference between malloc and calloc .Which is better ?
11
5791
by: lohith.matad | last post by:
Hi all, Though the purpose of both malloc() and calloc() is the same, and as we also know that calloc() initializes the alloacted locations to 'zero', and also that malloc() is used for bytes allocation whereas calloc() for chunk of memory allocation. Apart from these is there any strong reason that malloc() is prefered over calloc() or vice-versa? Looking forward for your clarrifications , possibly detailed.
6
4926
by: mthread | last post by:
Hi, I am learning C++ and I have been told that an object can be created either by using calloc or new. If it is true, can some one tell me what is the difference b/w using these two function calls.
13
2499
by: manish sahu | last post by:
difference between calloc() and malloc()
0
8721
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8642
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9069
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8964
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7804
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6558
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4653
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2385
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2024
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.