Allocate and zero-initialize an array with a user-defined size

suggest change

Read the requested count as a line, parse it, and check that the allocation-size calculation cannot overflow:

#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char line[128];

    fputs("Enter the number of elements: ", stdout);
    if (fgets(line, sizeof line, stdin) == NULL) {
        fputs("Could not read the element count\n", stderr);
        return EXIT_FAILURE;
    }

    errno = 0;
    char *end;
    unsigned long long input = strtoull(line, &end, 10);
    if (errno != 0 || end == line || (*end != '\n' && *end != '\0') ||
        input > SIZE_MAX / sizeof(int)) {
        fputs("Invalid or excessively large element count\n", stderr);
        return EXIT_FAILURE;
    }

    size_t count = (size_t)input;
    int *values = calloc(count, sizeof *values);
    if (count != 0 && values == NULL) {
        perror("calloc");
        return EXIT_FAILURE;
    }

    /* Use values[0] through values[count - 1]. */

    free(values);
    return EXIT_SUCCESS;
}

calloc initializes every bit in the allocated storage to zero and checks the multiplication of its two arguments for overflow. All-bits-zero represents the integer value zero, so every int element initially compares equal to zero.

A zero-size allocation may return either a null pointer or a pointer that can later be passed to free; neither result provides storage for an element. This example accepts a count of zero and never dereferences the result.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents