Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

strtoul — convert text to unsigned long

A guide to converting text to unsigned long and checking the result. The example demonstrates range checking and rejection of an unconsumed suffix.

Version: C23; repository compiler flag, production runtime not attested

Syntax

#include <stdlib.h>
unsigned long int strtoul(const char *restrict nptr, char **restrict endptr, int base);

strtoul converts the beginning of nptr to unsigned long, skipping leading whitespace and accepting + or -.

base: 2–36 or 0 (autodetection: 0 — octal, 0x/0X — hexadecimal, 0b/0B — binary in C23, otherwise decimal). C23 also accepts the binary prefix for base == 2.

Passing &end tells the function to store the address of the first unconsumed character in end. Passing NULL skips this store. No conversion means 0 and end == nptr. Overflow yields ULONG_MAX and errno == ERANGE: set errno = 0 first. Full conversion requires *end == '\0'.

Minus is not automatically an error: "-1" yields ULONG_MAX. To forbid negatives, reject minus after leading whitespace. A C23 compiler flag does not attest to the runtime library's C23 support.

Examples

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

int main(void)
{
    const char *text = "42";
    char *end;
    errno = 0;
    unsigned long value = strtoul(text, &end, 10);

    if (end == text || errno == ERANGE || *end != '\0') {
        puts("invalid");
        return EXIT_FAILURE;
    }

    printf("value=%lu\n", value);
    return EXIT_SUCCESS;
}

Result

value=42

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources