473,889 Members | 1,692 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
29 40445


Dan Pop wrote:
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"?


The Standard defines what occurs if the argument order is not "wrong".
What does the Standard state should you reverse this order?

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

Nov 13 '05 #11
On Tue, 04 Nov 2003 10:11:47 -0500
Al Bowers <xa******@rapid sys.com> wrote:
Dan Pop wrote:
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"?


The Standard defines what occurs if the argument order is not "wrong".
What does the Standard state should you reverse this order?


Instead of enough space for 100 elements 10 bytes long you will get
enough space for 10 elements 100 bytes long, for example. Fortunately
(or deliberately) both parameters to calloc are of type size_t, so
swapping them won't cause overflow problems, and last I checked x*y==y*x
--
Mark Gordon
Paid to be a Geek & a Senior Software Developer
Although my email address says spamtrap, it is real and I read it.
Nov 13 '05 #12
In <bo************ *@ID-169908.news.uni-berlin.de> Al Bowers <xa******@rapid sys.com> writes:


Dan Pop wrote:
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"?


The Standard defines what occurs if the argument order is not "wrong".
What does the Standard state should you reverse this order?


The obvious: that, instead of allocating space for N objects of M bytes
each, you allocate memory for M objects of N bytes each. That is
assuming that the "right" calloc call was calloc(N, M).

Now, pray tell, what is the difference between the two scenarios,
considering the general properties of malloc and friends?

If I want to allocate space for a string of 9 characters, which is the
"right" calloc call (calloc(1, 10) or calloc(10, 1)) and why?

Trivia quizz, for the beginner: there is a similar issue with the second
and third arguments of a fread or fwrite call, but there it does make a
real difference. Explain the difference between fread(buf, 1, 10, fp)
and fread(buf, 10, 1, fp).

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


Dan Pop wrote:
In <bo************ *@ID-169908.news.uni-berlin.de> Al Bowers <xa******@rapid sys.com> writes:
Dan Pop wrote:
Please elaborate. What happens if you get the calloc argument order
"wrong"?


The Standard defines what occurs if the argument order is not "wrong".
What does the Standard state should you reverse this order?

The obvious: that, instead of allocating space for N objects of M bytes
each, you allocate memory for M objects of N bytes each. That is
assuming that the "right" calloc call was calloc(N, M).


The Standard states that? Chapter and verse please!

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

Nov 13 '05 #14
"Dan Pop" <Da*****@cern.c h> wrote:
Trivia quizz, for the beginner: there is a similar issue with the second
and third arguments of a fread or fwrite call, but there it does make a
real difference. Explain the difference between fread(buf, 1, 10, fp)
and fread(buf, 10, 1, fp).


The only difference, in my experience, is in the integer value returned
from the fread function when it succeeds -- the former would return 10,
the latter would return 1.

I suppose if a read error or EOF occurred partway through the read,
the former fread call would give you more idea of exactly how much
data actually got read rather than the latter's simple yes/no reply.

--
Simon.
Nov 13 '05 #15

On Tue, 4 Nov 2003, Al Bowers wrote:

Dan Pop wrote:
Al Bowers <xa******@rapid sys.com> writes:
Dan Pop wrote: [re my first reason why I avoid calloc]Please elaborate. What happens if you get the calloc argument order
"wrong"?

The Standard defines what occurs if the argument order is not "wrong".
What does the Standard state should you reverse this order?


The obvious: that, instead of allocating space for N objects of M bytes
each, you allocate memory for M objects of N bytes each. That is
assuming that the "right" calloc call was calloc(N, M).


The Standard states that? Chapter and verse please!

Or is this your obvious conclusion?


For the record, I am almost positive that Dan Pop is exactly
right; getting calloc's arguments in the wrong order has absolutely
no ill effects. However, I see that some people *aren't* positively
of that opinion, and will demand proof of correctness.
Quod erat demonstrandum: it's easier to use malloc and avoid
the pedantic arguments, than use calloc and risk having to debate
obscure little points of the Standard. :-)

OTOH, Dan, if the argument order really *doesn't* matter, then
why does the Standard bother to specify which parameter is
which? [And why have 'calloc' take two arguments to begin with,
if it's *only* their product which matters? [Historical reasons.
But I'm interested to see what you'll say for the first question.]]

-Arthur
Nov 13 '05 #16
Arthur J. O'Dwyer <aj*@nospam.and rew.cmu.edu> scribbled the following:
On Tue, 4 Nov 2003, Al Bowers wrote:
Dan Pop wrote:
> Al Bowers <xa******@rapid sys.com> writes:
>>Dan Pop wrote: [re my first reason why I avoid calloc] >>>Please elaborate. What happens if you get the calloc argument order
>>>"wrong"?
>>
>>The Standard defines what occurs if the argument order is not "wrong".
>>What does the Standard state should you reverse this order?
>
> The obvious: that, instead of allocating space for N objects of M bytes
> each, you allocate memory for M objects of N bytes each. That is
> assuming that the "right" calloc call was calloc(N, M).
The Standard states that? Chapter and verse please!

Or is this your obvious conclusion?

For the record, I am almost positive that Dan Pop is exactly
right; getting calloc's arguments in the wrong order has absolutely
no ill effects. However, I see that some people *aren't* positively
of that opinion, and will demand proof of correctness.
Quod erat demonstrandum: it's easier to use malloc and avoid
the pedantic arguments, than use calloc and risk having to debate
obscure little points of the Standard. :-)
I am of the opinion that Dan Pop is completely correct. The effects of
reversing the order of calloc()'s parameters is nothing. Zippo. Nada.
Zilch. The fat lady has sung.
OTOH, Dan, if the argument order really *doesn't* matter, then
why does the Standard bother to specify which parameter is
which? [And why have 'calloc' take two arguments to begin with,
if it's *only* their product which matters? [Historical reasons.
But I'm interested to see what you'll say for the first question.]]


Which historical reasons would those be? Was there really a time when
it mattered, or was it just aesthetics? A remnant of B, BCPL, or an
even earlier language?
And as I've myself asked before, what's the point in gets() existing
in the first place?

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"Last year he disrespected me - and then he showed lack of respect."
- Anthony Mason
Nov 13 '05 #17
Al Bowers wrote:

Dan Pop wrote:
In <bo************ *@ID-169908.news.uni-berlin.de> Al Bowers <xa******@rapid sys.com> writes:
Dan Pop wrote:Please elaborate. What happens if you get the calloc argument order
"wrong"?
The Standard defines what occurs if the argument order is not "wrong".
What does the Standard state should you reverse this order?

The obvious: that,
instead of allocating space for N objects of M bytes
each, you allocate memory for M objects of N bytes each. That is
assuming that the "right" calloc call was calloc(N, M).


The Standard states that? Chapter and verse please!


My understanding of this part of the standard,
agrees with Dan Pop.

N869
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.
Nov 13 '05 #18
On Tue, 4 Nov 2003 15:27:31 -0500 (EST), "Arthur J. O'Dwyer"
<aj*@nospam.and rew.cmu.edu> wrote:
OTOH, Dan, if the argument order really *doesn't* matter, then
why does the Standard bother to specify which parameter is
which?


That's easy: because it's simpler than explaining that it doesn't
matter.

--
Al Balmer
Balmer Consulting
re************* ***********@att .net
Nov 13 '05 #19
On 4 Nov 2003 21:10:26 GMT, Joona I Palaste <pa*****@cc.hel sinki.fi>
wrote:
which? [And why have 'calloc' take two arguments to begin with,
if it's *only* their product which matters? [Historical reasons.
But I'm interested to see what you'll say for the first question.]]


Which historical reasons would those be? Was there really a time when
it mattered, or was it just aesthetics? A remnant of B, BCPL, or an
even earlier language?


I dunno about history, but it's a documentation aid - emphasizing that
you're asking for N spaces for an object of some certain size. Also
useful, since when calculating space requirements,mo st likely what you
want is N objects of type struct foo.

Now, the question is why doesn't malloc take two parameters?

--
Al Balmer
Balmer Consulting
re************* ***********@att .net
Nov 13 '05 #20

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

Similar topics

17
4902
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
6540
by: Rahul Gandhi | last post by:
Which one is more fast? malloc followed by memset or calloc
27
4782
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
2597
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
5805
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
11189
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
7514
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
13183
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
3707
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
11203
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10794
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...
0
10443
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
9612
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
7999
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
7151
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
5830
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
6029
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4650
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.