Article View: comp.std.c
Article #1186Re: calloc()
From: Barry Margolin
Date: Thu, 10 Sep 1992 16:41
Date: Thu, 10 Sep 1992 16:41
43 lines
2039 bytes
2039 bytes
In article <14455@goanna.cs.rmit.oz.au> ok@goanna.cs.rmit.oz.au (Richard A. O'Keefe) writes:
>Now I wonder: if I want to allocate an array with elements of known size
>but with number of elements not known until run-time, and if I don't really
>care what the initial contents are, _is_ there something in the standard to
>make
> p = calloc(NumberOfElements, sizeof *p)
>better than
> p = malloc(NumberOfElements * sizeof *p) ?
calloc() could compatibly be defined as:
void *calloc (size_t nelem, size_t size) {
void *result;
result = malloc(nelem * size);
if (result)
memset(result, 0, nelem * size);
return result;
}
>I thought I knew how C works, but if one is using a C that checks
>subscripts at run-time, what _might_ it do with a dynamic array allocated
>using malloc()? I'm not asking so much about actual systems as about what
>the standard requires/permits.
An array allocated with malloc() is conceptually an array of N 1-byte
elements. If calloc() were the primitive, malloc() could be defined as:
void *malloc (size_t size) {
return calloc(size, 1);
}
(this zeroes the returned memory unnecessarily, but there's nothing that
says that malloc() can't return zeroed memory).
C's rules for automatic conversion between an array and a pointer to its
first element, and its rules for equivalence of array[subscript] and
array+subscript, guarantee that there's no real need to distinguish whether
a block of memory was allocated as an array or not.
--
Barry Margolin
System Manager, Thinking Machines Corp.
barmar@think.com {uunet,harvard}!think!barmar
Technical Details
Message-ID:
<18ntqvINN8kd@early-bird.think.com>Path:
arc1-ca.pugleaf.net!sparky!uunet!spool.mu.edu!yale.edu!think.com!barmarReferences:
<14455@goanna.cs.rmit.oz.au>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!sparky!uunet!spool.mu.edu!yale.edu!think.com!barmar From: barmar@think.com (Barry Margolin) Newsgroups: comp.std.c Subject: Re: calloc() Date: 10 Sep 1992 16:41:03 GMT Organization: Thinking Machines Corporation, Cambridge MA, USA Lines: 43 Message-ID: <18ntqvINN8kd@early-bird.think.com> References: <14455@goanna.cs.rmit.oz.au> NNTP-Posting-Host: telecaster.think.com