2

G'day!

Usually if I was using malloc, I'd check for failure via:

int *A;

A=(int *)malloc(NUM_ELEMENTS*sizeof(int));
if (!A) {
    printf("mem failure, exiting \n");
    exit(EXIT_FAILURE);
}

Can I do the same thing for calloc, even though everything is assigned to 0? My gut feel is yes, because we'd be checking the mem address of A, and it doesn't matter that A[0] is 0, the mem address won't be null unless it failed.

James Adams
  • 678
  • 4
  • 11
  • 21

3 Answers3

3

Yes, you can error check calloc just like malloc. However, since calloc is fairly rock-solid failure wise, you usually don't need to do so, as explained here how can i know if calloc fails to initialize.

Community
  • 1
  • 1
phantom
  • 1,457
  • 7
  • 15
  • Including a check can still catch errors such as trying to allocate more memory than is available. I got caught out by running `calloc(big_calculated_number)` on a 32-bit architecture; checking whether calloc succeeded would have saved me a day's bug hunting! – Martin Smith May 18 '20 at 14:28
2

Yes your thinking is correct. You can do the same check with calloc for the reasons you stated.

JS1
  • 4,745
  • 1
  • 14
  • 19
2

OP's code works as well with malloc() as calloc().

But OP is incorrect with "mem address won't be null unless it failed."

If the requested allocation size is 0, the returned pointer may be NULL.

"If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object." C11dr §7.22.3.1 1

A more portable solution:

A = calloc(NUM_ELEMENTS, sizeof *A);
A = malloc(NUM_ELEMENTS * sizeof *A);

// Add size check
if (!A && NUM_ELEMENTS != 0) {
   fputs("mem failure, exiting \n", stderr);
   exit(EXIT_FAILURE);
}

Of course if NUM_ELEMENTS is always > 0, then this additional check is not needed.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256