Is calloc(4, 6) the same as calloc(6, 4)?

前端 未结 7 1632
南旧
南旧 2020-12-08 06:49

I\'m a beginner C programmer, and I assumed that this would be the case, but would like some affirmation if possible.

If they are the same, why not just take one arg

相关标签:
7条回答
  • 2020-12-08 07:39

    There is another way to look into this question.

    GNU C Library defines calloc like this:

    void * __libc_calloc (size_t n, size_t elem_size)
    {
      // ... (declarations)
    
      /* size_t is unsigned so the behavior on overflow is defined.  */
      bytes = n * elem_size;
    #define HALF_INTERNAL_SIZE_T \
      (((INTERNAL_SIZE_T) 1) << (8 * sizeof (INTERNAL_SIZE_T) / 2))
      if (__builtin_expect ((n | elem_size) >= HALF_INTERNAL_SIZE_T, 0))
        {
          if (elem_size != 0 && bytes / elem_size != n)
            {
              __set_errno (ENOMEM);
              return 0;
            }
        }
    
      void *(*hook) (size_t, const void *) = atomic_forced_read (__malloc_hook);
      if (__builtin_expect (hook != NULL, 0))
        {
          sz = bytes;
          mem = (*hook)(sz, RETURN_ADDRESS (0));
          if (mem == 0)
            return 0;
    
          return memset (mem, 0, sz);
        }
    
      sz = bytes;
    
      // ...more stuff, but no mention of n & elem_size anymore
    }
    

    So, at least in glibc these two calls do have identical effect.

    0 讨论(0)
提交回复
热议问题