home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #20 / NN_1992_20.iso / spool / comp / std / c / 2597 < prev    next >
Encoding:
Internet Message Format  |  1992-09-09  |  1.9 KB

  1. Path: sparky!uunet!munnari.oz.au!goanna!ok
  2. From: ok@goanna.cs.rmit.oz.au (Richard A. O'Keefe)
  3. Newsgroups: comp.std.c
  4. Subject: calloc()
  5. Message-ID: <14455@goanna.cs.rmit.oz.au>
  6. Date: 10 Sep 92 09:10:24 GMT
  7. Organization: Comp Sci, RMIT, Melbourne, Australia
  8. Lines: 40
  9.  
  10. I was correcting a student's C program today (I seem to be the debugger of
  11. choice, not dbx...) and while pointing out that
  12.     int *p;
  13.     p = calloc(n, sizeof (int));
  14.     p[0] = 20;
  15. would go BOOM! if calloc() ran out of memory, I asked "why does it matter
  16. that the new array be initialised to 0 bytes?"  The student said "it
  17. doesn't, but I want an _array_, and I thought you had to use calloc()
  18. for that, doesn't it keep an index?"  (In the student's vocabulary,
  19. index turned out to mean "the number of elements".)
  20.  
  21. On looking in Plauger & Brodie (I _know_ it isn't the standard; I ordered
  22. on through the department over a year ago) I find that they describe
  23. malloc() as allocating "a data object"  and calloc() as allocating
  24. "an array data object".
  25.  
  26. Now I wonder:  if I want to allocate an array with elements of known size
  27. but with number of elements not known until run-time, and if I don't really
  28. care what the initial contents are, _is_ there something in the standard to
  29. make
  30.     p = calloc(NumberOfElements, sizeof *p)
  31. better than
  32.     p = malloc(NumberOfElements * sizeof *p) ?
  33.  
  34. If there is, I'll switch to calloc() immediately.  In particular, I have
  35. been doing things like
  36.  
  37.     q = malloc(strlen(p)+1);
  38.     assert(q);
  39.     strcpy(q, p);
  40.     ... use q[i] ...
  41.  
  42. and some of the recent discussion about the old variable-length struct hack
  43. have me wondering whether this is strictly legitimate; should I use calloc()
  44. even here?  I thought I knew how C works, but if one is using a C that checks
  45. subscripts at run-time, what _might_ it do with a dynamic array allocated
  46. using malloc()?  I'm not asking so much about actual systems as about what
  47. the standard requires/permits.
  48. -- 
  49. You can lie with statistics ... but not to a statistician.
  50.