Check a malloc result in C

C

The allocation that nobody checks is the one that fails in production.

char *buf = malloc(len + 1);
if (buf == NULL) {
    fprintf(stderr, "out of memory allocating %zu bytes\n", len + 1);
    return -1;
}
memcpy(buf, src, len);
buf[len] = '\0';

More in Systems

Random picks