Article View: comp.std.c
Article #1184calloc()
From: Richard A. O'Keefe
Date: Thu, 10 Sep 1992 09:10
Date: Thu, 10 Sep 1992 09:10
40 lines
2031 bytes
2031 bytes
I was correcting a student's C program today (I seem to be the debugger of choice, not dbx...) and while pointing out that int *p; p = calloc(n, sizeof (int)); p[0] = 20; would go BOOM! if calloc() ran out of memory, I asked "why does it matter that the new array be initialised to 0 bytes?" The student said "it doesn't, but I want an _array_, and I thought you had to use calloc() for that, doesn't it keep an index?" (In the student's vocabulary, index turned out to mean "the number of elements".) On looking in Plauger & Brodie (I _know_ it isn't the standard; I ordered on through the department over a year ago) I find that they describe malloc() as allocating "a data object" and calloc() as allocating "an array data object". 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) ? If there is, I'll switch to calloc() immediately. In particular, I have been doing things like q = malloc(strlen(p)+1); assert(q); strcpy(q, p); ... use q[i] ... and some of the recent discussion about the old variable-length struct hack have me wondering whether this is strictly legitimate; should I use calloc() even here? 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. -- You can lie with statistics ... but not to a statistician.
Technical Details
Message-ID:
<14455@goanna.cs.rmit.oz.au>Path:
arc1-ca.pugleaf.net!sparky!uunet!munnari.oz.au!goanna!okShow Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!sparky!uunet!munnari.oz.au!goanna!ok From: ok@goanna.cs.rmit.oz.au (Richard A. O'Keefe) Newsgroups: comp.std.c Subject: calloc() Message-ID: <14455@goanna.cs.rmit.oz.au> Date: 10 Sep 92 09:10:24 GMT Organization: Comp Sci, RMIT, Melbourne, Australia Lines: 40