473,804 Members | 3,204 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Proper Use of calloc()


I went through my implementation' s (BSD) source code for
calloc(), and if no more than one object is being allocated,
the code will still execute the following if() (from
/usr/src/lib/libc/stdlib/calloc.c):

if (num && size && SIZE_T_MAX / num < size) {
errno = ENOMEM;
return NULL;
}

Is it better practice to just malloc(sizeof(t ype))
and then memset() the allocation, rather than calling
calloc() if only one object is being allocated?

What advantage is gained by the above if(), if malloc()
did not return NULL?

Brian
Nov 14 '05 #1
6 4100
brian <xb**********@c ox.net> writes:
I went through my implementation' s (BSD) source code for
calloc(), and if no more than one object is being allocated,
the code will still execute the following if() (from
/usr/src/lib/libc/stdlib/calloc.c):

if (num && size && SIZE_T_MAX / num < size) {
errno = ENOMEM;
return NULL;
}

Is it better practice to just malloc(sizeof(t ype)) and then memset()
the allocation, rather than calling calloc() if only one object is
being allocated?

What advantage is gained by the above if(), if malloc() did not return
NULL?


In my FreeBSD source tree this part of calloc() is *before* malloc() has
been called at all.

Obviously, the purpose of the particular if check is to avoid attempting
to malloc() a huge amount of space, that cannot be satisfied anyway.

This way malloc() doesn't even have to run, which probably saves a lot
of the work it would do attempting to allocate this large amount of
memory -- only to discover half-way through the allocation that it can't
be satisfied and revert all the work malloc() has done up to that point
just to return NULL to calloc().

- Giorgos

Nov 14 '05 #2
>brian <xb**********@c ox.net> writes:
I went through my implementation' s (BSD) source code for
calloc(), and if no more than one object is being allocated,
the code will still execute the following if() (from
/usr/src/lib/libc/stdlib/calloc.c):

if (num && size && SIZE_T_MAX / num < size) {
errno = ENOMEM;
return NULL;
} ... What advantage is gained by the above if(), if malloc() did not return
NULL?

In article <86************ @gothmog.gr>
Giorgos Keramidas <ke******@ceid. upatras.gr> writes:In my FreeBSD source tree this part of calloc() is *before* malloc() has
been called at all.
Indeed.
Obviously, the purpose of the particular if check is to avoid attempting
to malloc() a huge amount of space, that cannot be satisfied anyway.


Actually, it is more significant than that.

The two arguments to calloc() both have type "size_t", which is an
unsigned type. Suppose (for argument's sake, or because it also
happens to be true for the Intel-based FreeBSD anyway) that size_t
is an alias for a 32-bit unsigned integer type.

Suppose further that the parameters to calloc() are 10000000 (10
million) and 65536 -- i.e., 0x00989680 and 0x00010000. (Since
multiplication is commutative, it does not really matter which of
these is "num" and which is "size".) What is the product, num*size?

Clearly it *should* be 655360000000, or 0x9896800000, but this
exceeds 32 bits. Due to the nature of unsigned arithmetic, the
result will be reduced modulo $2^{32}$ (TeX notation), giving
0x96800000 or 2524971008.

Chances are this particular malloc() will then fail, but if it
succeeds -- which is more likely if I were to fiddle the numbers
above to come up with smaller final result -- the calloc()
routine will then bzero() the same amount of memory, and finally
return that pointer to its caller -- which will expect to have
much more memory than it actually does.

This could open a security hole, depending on the application in
question and what it does with the memory it believes it has.

The OP (identified only as "brian" above) did ask why this is done
even "if no more than one object is being allocated", i.e., if num
< 2. Since num is an unsigned type (size_t), this means either
num==0 or num==1. If num==0, the first part of the test -- "num
&&" -- fails and the "if" does nothing. So the work is only done
"questionab ly" if num==1 (and then if size > 0). In this case,
SIZE_T_MAX / num is SIZE_T_MAX / 1 which is clearly still SIZE_T_MAX,
and since "size" also has type size_t, the test SIZE_T_MAX < size
will fail. (The varable "size" is always less than or equal to
SIZE_T_MAX.) So in this case, the test is redundant -- but so
what?

One could argue that the code might be a hair faster for the num==1
cases if the test read:

if (num > 1 && size && SIZE_T_MAX / num < size)

which is probably true, but probably also not really very interesting
-- not unless profiling shows calls to calloc() with num==1 being
high on the time-consumption list.
--
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://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #3
Chris Torek wrote:
The OP (identified only as "brian" above) did ask why this is done
even "if no more than one object is being allocated", i.e., if num
< 2. Since num is an unsigned type (size_t), this means either
num==0 or num==1. If num==0, the first part of the test -- "num
&&" -- fails and the "if" does nothing. So the work is only done
"questionab ly" if num==1 (and then if size > 0). In this case,
SIZE_T_MAX / num is SIZE_T_MAX / 1 which is clearly still SIZE_T_MAX,
and since "size" also has type size_t, the test SIZE_T_MAX < size
will fail. (The varable "size" is always less than or equal to
SIZE_T_MAX.) So in this case, the test is redundant -- but so
what?

One could argue that the code might be a hair faster for the num==1
cases if the test read:

if (num > 1 && size && SIZE_T_MAX / num < size)

which is probably true, but probably also not really very interesting
-- not unless profiling shows calls to calloc() with num==1 being
high on the time-consumption list.


The original question was why use calloc() instead of malloc() with
memset() if only one object (i.e., num == 1) is being used. I asked
because you now have to go through the if() statement mentioned in
my op. You could avoid going through the if() by just calling malloc()
and setting the space to '\0' with memset.

Thus, this introduces the question, what is gained through going through
the if() statement? And thereby, asks, what is the proper use of
calloc()? Or when should calloc() be used instead of malloc() with
memset()?

The reason why I think that is an important question is because the if()
statement is the piece that differentiates malloc() with memset() from
calloc().

brian

p.s. The worse part about the if() statement is that it isn't easy to
read.
Nov 14 '05 #4
Chris Torek <no****@torek.n et> writes:
brian <xb**********@c ox.net> writes:
I went through my implementation' s (BSD) source code for
calloc(), [...]


In article <86************ @gothmog.gr>
Giorgos Keramidas <ke******@ceid. upatras.gr> writes:
Obviously, the purpose of the particular if check is to avoid attempting
to malloc() a huge amount of space, that cannot be satisfied anyway.


Actually, it is more significant than that.


Thanks!

That was a very enlightening read. More than the 'obvious' reason is
actually hidden in that if check and now I know about it :)

Nov 14 '05 #5
brian wrote:
Or when should calloc() be used instead of malloc() with
memset()?


Sometimes when I allocate memory for strings,
I want all the bytes zeroed. That's when I use calloc.

--
pete
Nov 14 '05 #6
pete wrote:

brian wrote:
Or when should calloc() be used instead of malloc() with
memset()?


Sometimes when I allocate memory for strings,
I want all the bytes zeroed. That's when I use calloc.

Why?


Brian Rodenborn
Nov 14 '05 #7

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

Similar topics

5
3646
by: Koster | last post by:
Sorry for the re-post, but my previous question was left unanswered. I have a question about the appropriateness of calloc. Consider an array of pointers to structs which need to be allocated space on the heap, for example: typedef struct myStruct *PMYSTRUCT; struct myStruct { int i; int j;
29
40431
by: David Hill | last post by:
Is there a difference between: /* code 1 */ struct sample test; test = malloc(sizeof(struct sample)); memset(&test, 0, sizeof(test)); /* code 2 */ struct sample test; test = calloc(1, sizeof(struct sample));
16
9002
by: laberth | last post by:
I've got a segmentation fault on a calloc and I don'tunderstand why? Here is what I use : typedef struct noeud { int val; struct noeud *fgauche; struct noeud *fdroit; } *arbre; //for those who don't speak french arbre means tree.
37
2586
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 ?
40
2539
by: boris | last post by:
Hi! I'm seeking some answers about what seems to be a memory leak. I have a loop that looks much like this: double *largeArray = (double*) calloc(); for (...) { printf("iteration #...\n"); for (...) { double *foo = (double*) calloc();
11
5801
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.
2
1751
by: chingfulan | last post by:
I have the following code and I can not figure out why Stg2In returns a null pointer? "Stg2In = (float *)calloc(9*DataLen, sizeof(float)); " while "Stg2Out = (float *)calloc(9*DataLen, sizeof(float));" is sucessful? Can anyone Help? Thx
14
7505
by: Roka100 | last post by:
Hi all, I tried 2 programs : #include <stdio.h> #include <string.h> 1, int main(void){ char *str = NULL;
171
4962
by: Raman | last post by:
Hi All, Here is a small Code, int main(void) { char *p=(char *) malloc(100); strcpy(p,"Test1234567890"); p=p+10; free(p);
0
9706
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
9579
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,...
1
10321
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,...
1
7620
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
6853
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
5522
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...
1
4300
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
2
3820
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2991
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.