Normally, one tests for the result of malloc to not be NULL to known whether memory allocation succeeded. With a series of malloc calls, this becomes a lengthy or tedious set of comparisons.
Instead, could one set errno = 0 at the top of the series of malloc calls, and then test for errno == ENOMEM at the end?
This assumes if any allocation fails, the program or function can't proceed and has to return/bail out. It also assumes the malloc calls are sequential and continuous, and that, as per the manual, malloc can only set errno to ENOMEM.
An example would be something like the following code:
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#define N (1 << 20)
int main()
{
double *a = NULL;
double *b = NULL;
double *c = NULL;
errno = 0;
a = malloc(N * sizeof *a);
b = malloc(N * sizeof *b);
c = malloc(N * sizeof *c);
if (errno == ENOMEM) {
perror(NULL);
free(a);
free(b);
free(c);
return EXIT_FAILURE;
}
errno = 0;
/* Do interesting stuff */
free(a);
free(b);
free(c);
return EXIT_SUCCESS;
}
(The example uses main(), but it could also be another function that simply can't be run, but the program might proceed otherwise, and no actual exit from the program happens, and the free() calls are necessary.)
I don't see any reason why this can't be done safely, but it's not an idiom I have come across, hence the question.