Skip to content

Copy a String in Uppercase

Allocate an uppercase copy of a C string with toupper and return it, or NULL if allocation fails.

Language: C

Added on: 21st August 2026

#include <ctype.h>
#include <stdlib.h>
#include <string.h>

char *upper_case(const char *str)
{
    size_t i;
    size_t n;
    char *buffer;

    if (str == NULL) {
        return NULL;
    }
    n = strlen(str);
    buffer = malloc(n + 1);
    if (buffer == NULL) {
        return NULL;
    }
    for (i = 0; i < n; i++) {
        buffer[i] = (char)toupper((unsigned char)str[i]);
    }
    buffer[n] = '\0';
    return buffer;
}

Caveats

Caller must free the result. Needs ctype.h, stdlib.h, and string.h. NULL input returns NULL.