473,659 Members | 2,690 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

malloc vs calloc

Is there a difference between:

/* code 1 */
struct sample test;
test = malloc(sizeof(s truct sample));
memset(&test, 0, sizeof(test));

/* code 2 */
struct sample test;
test = calloc(1, sizeof(struct sample));

Why would code 1 be chosen over code 2? I tend to see many instances of
code 1 in source code and hardly any instances of code 2.

Thanks
David
Nov 13 '05 #1
29 40381

"David Hill" <da***@wmol.com > wrote in message
news:GnEpb.7407 1$275.194415@at tbi_s53...
Is there a difference between:


Troll. Didn't you just ask this?

Tom
Nov 13 '05 #2

On Tue, 4 Nov 2003, David Hill wrote:

Is there a difference between:

/* code 1 */
struct sample test;
test = malloc(sizeof(s truct sample));
Whoops! Corrected the obvious typos below:

/* code 1 */
struct sample *test;
test = malloc(sizeof *test);
memset(test, 0, sizeof *test);
/* code 2 */
struct sample *test;
test = calloc(1, sizeof *test);

Why would code 1 be chosen over code 2? I tend to see many instances of
code 1 in source code and hardly any instances of code 2.


OMMV, but I personally avoid 'calloc', along with some library
functions such as 'memmove', because I think their *exact* effects
are obscure, and I don't ever feel like reading manpages when I
don't have to.

In particular for your example, 'calloc' takes two arguments whose
order matters -- so I'd have to get that right, where with 'malloc'
I don't. Ease of use.

Secondly, 'calloc' tries to set all the newly allocated bytes to zero.
That generally takes O(n) time. Now C in general has a very close
correspondence between C-language statements and machine-level
instructions, and I feel that if I'm going to be performing a very
expensive setup step like "set this whole block to zero," that's
something that should *not* be hidden away inside a library function
call. The 'malloc'/'memset' idiom makes the cost of setting '*test'
to zero slightly more noticeable.

Those are the two big reasons I don't use 'calloc', but there's
one more: it is rarely the right tool for the job.

In fact, *neither* of those fragments is going to do what you want,
in the general case: setting a struct's bytes to all zero isn't the
same as setting each member of that struct to zero, especially when
it comes to pointers and floating-point numbers. There's no easy
way to set each member of a dynamically allocated 'struct' to zero,
though -- you have to do it one-by-one.

HTH,
-Arthur
Nov 13 '05 #3
"David Hill" <da***@wmol.com > writes:
Is there a difference between:

/* code 1 */
struct sample test;
test = malloc(sizeof(s truct sample));
`test' is not a pointer, so this assignment is invalid. I will
assume you meant to declare `test' as type `struct sample *'.

When calling malloc(), I recommend using the sizeof operator on
the object you are allocating, not on the type. For instance,
*don't* write this:

int *x = malloc (sizeof (int) * 128); /* Don't do this! */

Instead, write it this way:

int *x = malloc (sizeof *x * 128);

There's a few reasons to do it this way:

* If you ever change the type that `x' points to, it's not
necessary to change the malloc() call as well.

This is more of a problem in a large program, but it's still
convenient in a small one.

* Taking the size of an object makes writing the statement
less error-prone. You can verify that the sizeof syntax is
correct without having to look at the declaration.
memset(&test, 0, sizeof(test));
`&test' would be correct if `test' didn't have a pointer type,
but since you meant it to have a pointer type (or why would you
assign it the result of malloc()) this should be changed to
memset(test, 0, sizeof *test);
/* code 2 */
struct sample test;
test = calloc(1, sizeof(struct sample));
Again, `test' needs to have a pointer type for this to be
reasonable.
Why would code 1 be chosen over code 2? I tend to see many instances of
code 1 in source code and hardly any instances of code 2.


The latter is more straightforward . It might even be faster if
the implementation has a source of pre-zeroed storage.

Often neither is portably correct, because pointer and
floating-point types, among others, need not have a null pointer
or zero value when set to all-bits-zero.
--
"I hope, some day, to learn to read.
It seems to be even harder than writing."
--Richard Heathfield
Nov 13 '05 #4
David Hill wrote:
Is there a difference between:

/* code 1 */
struct sample test;
test = malloc(sizeof(s truct sample));
memset(&test, 0, sizeof(test));
Well, the above is just plain wrong! ITYM:

struct sample * test;
test = malloc(sizeof *test);
if (test == NULL) {
/* take appropriate action */
}
memset(test, 0, sizeof *test);

/* code 2 */
struct sample test;
test = calloc(1, sizeof(struct sample));
Same problem. ITYM:

struct sample * test;
test = calloc(1, sizeof *test);
/* appropriate test for calloc failure */


Why would code 1 be chosen over code 2? I tend to see many instances of
code 1 in source code and hardly any instances of code 2.


Considering the fact that it's wrong [;-)], I doubt it.

Once corrected, however, they are equivalent.

HTH,
--ag

--
Artie Gold -- Austin, Texas
Oh, for the good old days of regular old SPAM.

Nov 13 '05 #5
On Mon, 3 Nov 2003 22:02:50 -0500 (EST), "Arthur J. O'Dwyer"
<aj*@nospam.and rew.cmu.edu> wrote in comp.lang.c:

On Tue, 4 Nov 2003, David Hill wrote:

Is there a difference between:

/* code 1 */
struct sample test;
test = malloc(sizeof(s truct sample));
Whoops! Corrected the obvious typos below:

/* code 1 */
struct sample *test;
test = malloc(sizeof *test);
memset(test, 0, sizeof *test);
/* code 2 */
struct sample *test;
test = calloc(1, sizeof *test);

Why would code 1 be chosen over code 2? I tend to see many instances of
code 1 in source code and hardly any instances of code 2.


OMMV, but I personally avoid 'calloc', along with some library
functions such as 'memmove', because I think their *exact* effects
are obscure, and I don't ever feel like reading manpages when I
don't have to.


You think right about calloc(), wrong about memmove(). The effects of
the latter are perfectly defined.
In particular for your example, 'calloc' takes two arguments whose
order matters -- so I'd have to get that right, where with 'malloc'
I don't. Ease of use.


The order of the arguments to calloc() does NOT matter. Nor do the
exact values. ONLY the product of the two values matters.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
Nov 13 '05 #6


Arthur J. O'Dwyer wrote:
On Tue, 4 Nov 2003, David Hill wrote:
Is there a difference between:

/* code 1 */
struct sample test;
test = malloc(sizeof(s truct sample));

Whoops! Corrected the obvious typos below:

/* code 1 */
struct sample *test;
test = malloc(sizeof *test);
memset(test, 0, sizeof *test);
/* code 2 */
struct sample *test;
test = calloc(1, sizeof *test);
Why would code 1 be chosen over code 2? I tend to see many instances of
code 1 in source code and hardly any instances of code 2.


.....snip...... ..

In fact, *neither* of those fragments is going to do what you want,
in the general case: setting a struct's bytes to all zero isn't the
same as setting each member of that struct to zero, especially when
it comes to pointers and floating-point numbers. There's no easy
way to set each member of a dynamically allocated 'struct' to zero,
though -- you have to do it one-by-one.


You can assign a struct object the value of a static struct object.
I'm not sure if this is included in your reference of one-by-one.

#include <stdio.h>

struct test
{
int i;
double d;
int *ip;
} init;

int main(void)
{
struct test a = init;

printf("a.i = %d\na.d = %f\na.ip is%s a null pointer\n",
a.i,a.d,(a.ip== NULL)?"":" not");
return 0;
}

--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapi dsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 13 '05 #7

"David Hill" <da***@wmol.com > schrieb im Newsbeitrag
news:GnEpb.7407 1$275.194415@at tbi_s53...
Is there a difference between:

/* code 1 */
struct sample test;
test = malloc(sizeof(s truct sample));
memset(&test, 0, sizeof(test));

/* code 2 */
struct sample test;
test = calloc(1, sizeof(struct sample));

Why would code 1 be chosen over code 2? I tend to see many instances of
code 1 in source code and hardly any instances of code 2.


I think, zeroing a struct with either calloc() or malloc()/memset() is a Bad
Idea :). If you need just one struct, use

struct sample test = {0};

Which is guaranteed to fill all the members with the appropriate zero values
(NULL for pointers, 0.0 for floating point values etc).
And if you have to malloc() an array of structs and zero them it's better to
write something like
(snippet only, headers, #defines etc omitted)

size_t i;
struct sample empty = {0};
struct sample *test = malloc(NUMBER_O F_STRUCTS_WANTE D * sizeof *test);
if(test)
{
for(i = 0; i < NUMBER_OF_STRUC TS_WANTED; i++)
{
test[i] = empty;
}
/*do something with test*/
free(test);
}

Using an initializer gives you also the possibility to initialize your
structs to non-zero values:

struct tag_test
{
size_t size;
int available;
char some_text[SOME_SIZE];
}init_struct = {sizeof init_struct, 1, "Item"};
Robert
Nov 13 '05 #8
"Tom St Denis" <to********@iah u.ca> wrote:
"David Hill" <da***@wmol.com > wrote:
Is there a difference between:
Troll.


I don't think so.
Didn't you just ask this?


No, he didn't. It was somebody else:

# From: rihad <ri***@mail.r u>
# Newsgroups: comp.lang.c
# Subject: calloc(1,1) vs. *malloc(1)=0
# Date: Thu, 30 Oct 2003 00:12:16 +0400
# Message-ID: <ai************ *************** *****@4ax.com>

Regards
--
Irrwahn
(ir*******@free net.de)
Nov 13 '05 #9
In <Pi************ *************** ********@unix41 .andrew.cmu.edu > "Arthur J. O'Dwyer" <aj*@nospam.and rew.cmu.edu> writes:

In particular for your example, 'calloc' takes two arguments whose
order matters -- so I'd have to get that right, where with 'malloc'
I don't.
Please elaborate. What happens if you get the calloc argument order
"wrong"?
Secondly, 'calloc' tries to set all the newly allocated bytes to zero.
That generally takes O(n) time. Now C in general has a very close
corresponden ce between C-language statements and machine-level
instructions , and I feel that if I'm going to be performing a very
expensive setup step like "set this whole block to zero," that's
something that should *not* be hidden away inside a library function
call. The 'malloc'/'memset' idiom makes the cost of setting '*test'
to zero slightly more noticeable.
Isn't it still hidden away inside a library function call?
Those are the two big reasons I don't use 'calloc', but there's
one more: it is rarely the right tool for the job.


It's not that exotic to initialise an object to all zeroes at the very
point you bring it into existence. calloc can achieve this for quite a
wide range of objects (only floating point and pointers can't be
*portably* set to zero this way, but, if your code is already
non-portable, this is the least of your worries: conforming
implementations where all bits zero don't work as expected for floating
point and pointers are few and far between).

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #10

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

Similar topics

17
4881
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
6502
by: Rahul Gandhi | last post by:
Which one is more fast? malloc followed by memset or calloc
27
4749
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...
37
2550
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
5785
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.
8
11175
by: venkatesh | last post by:
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?
14
7484
by: Roka100 | last post by:
Hi all, I tried 2 programs : #include <stdio.h> #include <string.h> 1, int main(void){ char *str = NULL;
318
12926
by: jacob navia | last post by:
Rcently I posted code in this group, to help a user that asked to know how he could find out the size of a block allocated with malloc. As always when I post something, the same group of people started to try to find possible errors, a harmless passtime they seem to enjoy. One of their remarks was that I used "int" instead of "size_t" for the input of my allocator function.
46
3657
by: lovecreatesbea... | last post by:
Do you prefer malloc or calloc? p = malloc(size); Which of the following two is right to get same storage same as the above call? p = calloc(1, size); p = calloc(size, 1);
0
8427
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
8332
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
8627
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7356
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
6179
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
5649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4175
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4335
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1737
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.