473,854 Members | 1,762 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 40439

On Tue, 4 Nov 2003, Joona I Palaste wrote:

Arthur J. O'Dwyer <aj*@nospam.and rew.cmu.edu> scribbled the following:

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?


That by the time C was being standardized, 'calloc' had already
been defined for more than 10 years as taking two arguments. (My
copy of K&R1 is back! ;-)
Incidentally, K&R1 describes 'calloc' as returning a block of
memory sized "for n objects of the specified size" and suitably
aligned "for the object in question." Thus, it's conceivable
that certain pre-standard implementations might have been
optimized to return less-strictly-aligned pointers from

calloc(1024, sizeof(char))

than from

calloc(1, sizeof(my_1024_ byte_object))

--hence the pair of arguments. But I have no hard evidence
to support such a conclusion.

And as I've myself asked before, what's the point in gets()
existing in the first place?


Same reason -- it was used in a lot of existing code, and the
standards committee didn't want to break that code. Sure, it
was a dumb function to create in the *very* first place, but
it probably got entrenched before anyone noticed how awful it
really could be. And by the time it was mentioned in K&R, there
was no way anyone was going to be able to displace it.

-Arthur

Nov 13 '05 #21
On Tue, 4 Nov 2003 15:27:31 -0500 (EST), in comp.lang.c , "Arthur J.
O'Dwyer" <aj*@nospam.and rew.cmu.edu> wrote:
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.


I tend to agree. However, out of interest, what if the platform wanted
a specific alignment, or if there were padding after a structure's
last member?

Is it not the case that calloc (8, 7) might create eight 7 byte
objects aligned to 8 byte boundaries, while calloc(7,8) might create
seven 8 byte objects similarly aligned. The former block would then be
larger than the latter possibly?

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/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 13 '05 #22
Mark McIntyre wrote:

On Tue, 4 Nov 2003 15:27:31 -0500 (EST), in comp.lang.c , "Arthur J.
O'Dwyer" <aj*@nospam.and rew.cmu.edu> wrote:
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.


I tend to agree. However, out of interest, what if the platform wanted
a specific alignment, or if there were padding after a structure's
last member?

Is it not the case that calloc (8, 7) might create eight 7 byte
objects aligned to 8 byte boundaries, while calloc(7,8) might create
seven 8 byte objects similarly aligned. The former block would then be
larger than the latter possibly?


calloc is creating memory for an array.
There's no padding between elements in an array.

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 freed or
reallocated).
Nov 13 '05 #23
In article <Pi************ *************** *******@unix47. andrew.cmu.edu>
Arthur J. O'Dwyer <aj*@nospam.and rew.cmu.edu> writes:
Incidentally, K&R1 describes 'calloc' as returning a block of
memory sized "for n objects of the specified size" and suitably
aligned "for the object in question." Thus, it's conceivable
that certain pre-standard implementations might have been
optimized to return less-strictly-aligned pointers from

calloc(1024, sizeof(char))

than from

calloc(1, sizeof(my_1024_ byte_object))

--hence the pair of arguments. But I have no hard evidence
to support such a conclusion.


As further evidence that this was at least in the mind of whoever
wrote calloc(), in the ancient Unix C libraries (Phototypesette r
V6, maybe earlier?) one was *supposed* to free calloc()ed memory
with the companion function cfree(). But many programs just called
free() anyway -- which worked because the actual implementation of
calloc() just called malloc() -- and I imagine the idea of a separate
allocator was abandoned.

A number of the oddities and excrescences in both C and Unix are
there simply because a bad idea got entrenched. Which, interestingly,
relates to the discussion (if one can call it that) going on
elsethread, about whether to write portable code or "just get the
job done at the moment" code and worry about portability later.
It is true that "get the job done any dirty, hacky ol' way" *can*
improve one's time-to-market, which some -- perhaps too many --
companies believe is paramount, far more important than any kind
of reliability or maintainability . They may even be right (which
would explain the sad state of so much software). Yet, paradoxically,
writing portable code in the first place can *also* improve one's
time-to-market. A great deal depends on the situation, and situations
have a way of changing unexpectedly.

(My personal preference is to write code that is "as portable as
seems possible and cost-effective" from the start, so that it has
a good chance of porting when the situation does change. I think
that the time required to learn what it takes to achieve this is
well-spent. But others -- even some I consider reasonable people
-- do disagree at times. :-) )
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://67.40.109.61/torek/index.html (for the moment)
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 13 '05 #24
In <Pi************ *************** *******@unix47. andrew.cmu.edu> "Arthur J. O'Dwyer" <aj*@nospam.and rew.cmu.edu> writes:

On Tue, 4 Nov 2003, Joona I Palaste wrote:

Arthur J. O'Dwyer <aj*@nospam.and rew.cmu.edu> scribbled the following:
>
> 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?


That by the time C was being standardized, 'calloc' had already
been defined for more than 10 years as taking two arguments. (My
copy of K&R1 is back! ;-)
Incidentally, K&R1 describes 'calloc' as returning a block of
memory sized "for n objects of the specified size" and suitably
aligned "for the object in question." Thus, it's conceivable
that certain pre-standard implementations might have been
optimized to return less-strictly-aligned pointers from

calloc(1024, sizeof(char))

than from

calloc(1, sizeof(my_1024_ byte_object))

--hence the pair of arguments. But I have no hard evidence
to support such a conclusion.


Nevertheless, your analysis makes sense.
And as I've myself asked before, what's the point in gets()
existing in the first place?


Same reason -- it was used in a lot of existing code, and the
standards committee didn't want to break that code. Sure, it
was a dumb function to create in the *very* first place, but
it probably got entrenched before anyone noticed how awful it
really could be. And by the time it was mentioned in K&R, there
was no way anyone was going to be able to displace it.


This still doesn't explain why C89 (or even C99) didn't deprecate it.

BTW, the C standard library doesn't contain any properly designed function
for reading a line of input from a text stream. As a result, many
programmers invent their own wheel, which is downright silly. fgets()
is safe but it is also a pain in the ass to use correctly.

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


Dan Pop wrote:
In <bo************ *@ID-169908.news.uni-berlin.de> Al Bowers <xa******@rapid sys.com> writes:
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?


How can you construct a "right" way?
One visualizes the allocation as an object of 1 string of 9 characters.
Thus:
calloc(1,10);

or One visualize the allocation 1 string of 9 characters as a allocation
of an array of 10 characters. Thus:
calloc(10,1);
Either way, the allocation is the same.

Consider a more complex example; an allocation of an array of a struct
type. Using the standard as as guide, the first argument would be the
nember of structs in the array and the second argument would be the
size of the struct. If one is haphazard in the order of the arguments,
the allocation would be the same, however, I would consider it sloppy
code, which may lead to code management confusion.

This code seq faults. Why?
I see, variable b, the first argument in calloc, does not
represent the numb of structs in the array.

#include <stdlib.h>
#include <stdio.h>

#define STRUCT_NR 7

struct test
{
char name[80];
char addr[80];
} init = {{"NAME GOES HERE"},{"ADDRES S GOES HERE"}};

int main(void)
{
size_t a = STRUCT_NR, b = sizeof(struct test),i;
struct test *s;

if((s = calloc(b,a)) == NULL) return EXIT_FAILURE;
/* Ok, calloc 1st argument, b, should represent num. structs*/
for(i = 0; i < b;i++) s[i] = init;
printf("s[0].name is %s\ns[0].addr is %s\n", s[0].name,s[0].addr);
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 #26
In <bo************ *@ID-169908.news.uni-berlin.de> Al Bowers <xa******@rapid sys.com> writes:


Dan Pop wrote:
In <bo************ *@ID-169908.news.uni-berlin.de> Al Bowers <xa******@rapid sys.com> writes:
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?


How can you construct a "right" way?
One visualizes the allocation as an object of 1 string of 9 characters.
Thus:
calloc(1,10) ;

or One visualize the allocation 1 string of 9 characters as a allocation
of an array of 10 characters. Thus:
calloc(10,1) ;
Either way, the allocation is the same.


You have to ask this question to the poster who thought that there is
a right way and a wrong way of specifying calloc's arguments. I didn't
put the word right between double quotes just because I cannot control
my fingers while typing ;-)
Consider a more complex example; an allocation of an array of a struct
type. Using the standard as as guide, the first argument would be the
nember of structs in the array and the second argument would be the
size of the struct. If one is haphazard in the order of the arguments,
the allocation would be the same, however, I would consider it sloppy
code, which may lead to code management confusion.
Which has exactly nothing to do with the program's correctness, from the
standard's point of view.
This code seq faults. Why?
I see, variable b, the first argument in calloc, does not
represent the numb of structs in the array.

#include <stdlib.h>
#include <stdio.h>

#define STRUCT_NR 7

struct test
{
char name[80];
char addr[80];
} init = {{"NAME GOES HERE"},{"ADDRES S GOES HERE"}};

int main(void)
{
size_t a = STRUCT_NR, b = sizeof(struct test),i;
struct test *s;

if((s = calloc(b,a)) == NULL) return EXIT_FAILURE;
/* Ok, calloc 1st argument, b, should represent num. structs*/
for(i = 0; i < b;i++) s[i] = init;
printf("s[0].name is %s\ns[0].addr is %s\n", s[0].name,s[0].addr);
return 0;
}


The bug is NOT in the calloc() call. I entirely agree that calling
calloc according to its description has a great impact on program's
readability/maintenability, but this is NOT a correctness issue. The
code is *always* correct if the programmer is consistent in his usage
of the two arguments of calloc(), even if his usage is not the one
described in the standard.

In your example, if you used meaningful names for a and b, like nelem and
size, the bug would have been immediately obvious, despite the unorthodox
calloc call. It is your silly naming choice that obfuscates the bug: one
shouldn't derive the meaning of a variable from its position in a calloc
call.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #27
In <3f************ **********@news .optusnet.com.a u> "Simon Biber" <ne**@ralminNOS PAM.cc> writes:
"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.


Any time I post a trivia quizz for the beginners, one of the regulars
feels compelled to spoil it...

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #28
Dan Pop wrote:
In <3f************ **********@news .optusnet.com.a u> "Simon Biber"
<ne**@ralminNOS PAM.cc> writes:
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.


Any time I post a trivia quizz for the beginners, one of the regulars
feels compelled to spoil it...


....and then some other regular adds to your misery by maliciously correcting
your misspelling of "quiz". Life's a bitch, isn't it? :-)

Oh, I nearly forgot. All spelling flames must contain a spelling error, so
here's min.

--
Richard Heathfield : bi****@eton.pow ernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 13 '05 #29
Dan Pop <Da*****@cern.c h> wrote:
In <3f************ **********@news .optusnet.com.a u> "Simon Biber" <ne**@ralminNOS PAM.cc> writes:
"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.

Any time I post a trivia quizz for the beginners, one of the regulars
feels compelled to spoil it...


Maybe because they fail to see the connection between this mysterious
"quizz" thing and a "quiz" :-)

Alex
Nov 13 '05 #30

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

Similar topics

17
4900
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
6538
by: Rahul Gandhi | last post by:
Which one is more fast? malloc followed by memset or calloc
27
4779
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
2595
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
11188
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
7511
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
13151
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
3704
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
9752
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
10373
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
9525
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
7921
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
7083
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
5753
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
5946
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4565
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
3
3193
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.