Reputation: 748
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.
Upvotes: 3
Views: 14823
Reputation: 154335
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.
Upvotes: 2
Reputation: 1455
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.
Upvotes: 3
Reputation: 4767
Yes your thinking is correct. You can do the same check with calloc
for the reasons you stated.
Upvotes: 2