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

  1. Path: sparky!uunet!spool.mu.edu!yale.edu!think.com!barmar
  2. From: barmar@think.com (Barry Margolin)
  3. Newsgroups: comp.std.c
  4. Subject: Re: calloc()
  5. Date: 10 Sep 1992 16:41:03 GMT
  6. Organization: Thinking Machines Corporation, Cambridge MA, USA
  7. Lines: 43
  8. Message-ID: <18ntqvINN8kd@early-bird.think.com>
  9. References: <14455@goanna.cs.rmit.oz.au>
  10. NNTP-Posting-Host: telecaster.think.com
  11.  
  12. In article <14455@goanna.cs.rmit.oz.au> ok@goanna.cs.rmit.oz.au (Richard A. O'Keefe) writes:
  13. >Now I wonder:  if I want to allocate an array with elements of known size
  14. >but with number of elements not known until run-time, and if I don't really
  15. >care what the initial contents are, _is_ there something in the standard to
  16. >make
  17. >    p = calloc(NumberOfElements, sizeof *p)
  18. >better than
  19. >    p = malloc(NumberOfElements * sizeof *p) ?
  20.  
  21. calloc() could compatibly be defined as:
  22.  
  23. void *calloc (size_t nelem, size_t size) {
  24.     void *result;
  25.     result = malloc(nelem * size);
  26.     if (result)
  27.         memset(result, 0, nelem * size);
  28.     return result;
  29. }
  30.  
  31. >I thought I knew how C works, but if one is using a C that checks
  32. >subscripts at run-time, what _might_ it do with a dynamic array allocated
  33. >using malloc()?  I'm not asking so much about actual systems as about what
  34. >the standard requires/permits.
  35.  
  36. An array allocated with malloc() is conceptually an array of N 1-byte
  37. elements.  If calloc() were the primitive, malloc() could be defined as:
  38.  
  39. void *malloc (size_t size) {
  40.     return calloc(size, 1);
  41. }
  42.  
  43. (this zeroes the returned memory unnecessarily, but there's nothing that
  44. says that malloc() can't return zeroed memory).
  45.  
  46. C's rules for automatic conversion between an array and a pointer to its
  47. first element, and its rules for equivalence of array[subscript] and
  48. array+subscript, guarantee that there's no real need to distinguish whether
  49. a block of memory was allocated as an array or not.
  50. -- 
  51. Barry Margolin
  52. System Manager, Thinking Machines Corp.
  53.  
  54. barmar@think.com          {uunet,harvard}!think!barmar
  55.