Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/MicrosoftDocs/cpp-docs/llms.txt

Use this file to discover all available pages before exploring further.

The Microsoft C Runtime Library (CRT) organizes its functions into well-defined categories, each addressing a core area of systems programming. Whether you are reading files, manipulating strings, managing heap memory, computing mathematical results, or controlling process lifetime, the CRT provides both classic C functions and their modern, security-enhanced _s suffix counterparts. This page covers the most commonly used functions from each major category with practical code examples.

I/O Functions

The CRT I/O category encompasses console I/O, formatted output, file streams, and binary file access. All standard C stream functions are supported, along with Windows-specific extensions.
#include <stdio.h>

int main(void) {
    int age;
    char name[64];

    printf("Enter your name: ");
    // scanf_s is the secure variant — requires buffer size for %s
    scanf_s("%63s", name, (unsigned)sizeof(name));

    printf("Enter your age: ");
    scanf_s("%d", &age);

    printf("Hello, %s! You are %d years old.\n", name, age);
    return 0;
}
Key I/O functions:
FunctionDescription
printf / printf_sFormatted output to stdout
scanf / scanf_sFormatted input from stdin
fopen / fopen_sOpen a file stream
fread / fwriteBinary block read/write
fcloseClose a file stream
fseek / ftellStream positioning
fgets / fputsLine-oriented text I/O

String Functions

String functions handle byte strings, wide strings, and multi-byte character sequences. Always prefer the _s variants in new code to avoid buffer overruns.
#include <stdio.h>
#include <string.h>

int main(void) {
    char dest[32];
    const char* src = "Hello, MSVC!";

    // Safe copy with explicit buffer size
    strcpy_s(dest, sizeof(dest), src);
    printf("Copied: %s\n", dest);

    // Safe concatenation
    strcat_s(dest, sizeof(dest), " (CRT)");
    printf("Appended: %s\n", dest);

    // Length
    printf("Length: %zu\n", strlen(dest));

    // Safe formatted string
    char msg[64];
    sprintf_s(msg, sizeof(msg), "Value = %d, Float = %.2f", 42, 3.14);
    printf("%s\n", msg);

    // Safe string scan
    int n; float f;
    sscanf_s(msg, "Value = %d, Float = %f", &n, &f);
    printf("Parsed: n=%d, f=%.2f\n", n, f);

    return 0;
}
strcpy_s, strcat_s, and sprintf_s all take an explicit rsize_t (or size_t) buffer-size parameter as their second argument. If the source string would overflow the destination, they invoke the invalid parameter handler rather than silently writing past the buffer.
Key string functions:
FunctionSafe VariantDescription
strcpystrcpy_sCopy a string
strcatstrcat_sAppend a string
strlenString length
strcmpCompare strings
sprintfsprintf_sFormat to string
sscanfsscanf_sParse from string
strtokstrtok_sTokenize a string
strupr_strupr_sConvert to uppercase

Memory Functions

Memory management functions cover heap allocation, deallocation, and buffer manipulation. MSVC also provides aligned allocation variants.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    // Allocate uninitialized memory
    int* arr = (int*)malloc(10 * sizeof(int));
    if (arr == NULL) { return 1; }

    for (int i = 0; i < 10; i++) arr[i] = i * i;

    // Resize the allocation
    arr = (int*)realloc(arr, 20 * sizeof(int));
    if (arr == NULL) { return 1; }
    for (int i = 10; i < 20; i++) arr[i] = i * i;

    printf("arr[15] = %d\n", arr[15]);
    free(arr);

    // Allocate zeroed memory
    double* buf = (double*)calloc(5, sizeof(double));
    if (buf) {
        printf("buf[0] = %f (should be 0.0)\n", buf[0]);
        free(buf);
    }
    return 0;
}
Never mix allocators: memory allocated with malloc must be freed with free; new with delete; and new[] with delete[]. Mixing causes undefined behavior and heap corruption.

Math Functions

The CRT math library is declared in <math.h> (C) or <cmath> (C++). All standard C99 math functions are supported.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int main(void) {
    double x = 2.0;

    printf("sqrt(%.1f) = %.6f\n",  x, sqrt(x));
    printf("pow(%.1f, 10) = %.0f\n", x, pow(x, 10.0));
    printf("sin(pi/2) = %.6f\n",   sin(3.14159265358979 / 2.0));
    printf("cos(0) = %.6f\n",      cos(0.0));
    printf("fabs(-7.5) = %.1f\n",  fabs(-7.5));
    printf("floor(3.9) = %.1f\n",  floor(3.9));
    printf("ceil(3.1) = %.1f\n",   ceil(3.1));
    printf("fmod(10.0, 3.0) = %.1f\n", fmod(10.0, 3.0));

    // Integer absolute value
    int neg = -42;
    printf("abs(%d) = %d\n", neg, abs(neg));

    return 0;
}
Key math functions:
FunctionDescription
sqrt / sqrtfSquare root
pow / powfPower
sin, cos, tanTrigonometric
log, log10, log2Logarithms
floor, ceil, roundRounding
fabs / absAbsolute value
fmodFloating-point remainder
expExponential (e^x)

Time Functions

Time functions are declared in <time.h>. Use the _s variants (localtime_s, gmtime_s) to avoid the non-reentrant behavior of the legacy functions.
#include <stdio.h>
#include <time.h>

int main(void) {
    // Current time as calendar time
    time_t now = time(NULL);
    printf("time_t value: %lld\n", (long long)now);

    // CPU time consumed by this process
    clock_t start = clock();
    // ... do work ...
    clock_t end = clock();
    double cpu_sec = (double)(end - start) / CLOCKS_PER_SEC;
    printf("CPU time: %.6f seconds\n", cpu_sec);

    // Convert to local time (thread-safe _s variant)
    struct tm local_tm;
    if (localtime_s(&local_tm, &now) == 0) {
        char buf[64];
        strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &local_tm);
        printf("Local time: %s\n", buf);
    }

    // Convert to UTC time
    struct tm utc_tm;
    if (gmtime_s(&utc_tm, &now) == 0) {
        char buf[64];
        strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%SZ", &utc_tm);
        printf("UTC time: %s\n", buf);
    }

    return 0;
}
localtime_s and gmtime_s are the thread-safe, secure replacements for localtime and gmtime. The legacy versions return a pointer to a static buffer that is shared across threads — always use _s variants in multi-threaded code.

Process Control Functions

Process control functions manage program termination, registered exit handlers, and subprocess execution.
#include <stdio.h>
#include <stdlib.h>

void cleanup_handler(void) {
    printf("Cleanup: releasing resources...\n");
}

void second_handler(void) {
    printf("Cleanup: second handler (runs before first)\n");
}

int main(void) {
    // Register cleanup functions — called in LIFO order at normal exit
    atexit(cleanup_handler);
    atexit(second_handler);

    printf("Program running...\n");

    // Normal exit: flushes stdio, calls atexit handlers, closes files
    // exit(0);

    // _Exit / _exit: immediate termination, NO atexit handlers called
    // _exit(0);

    // Run a system command (use with caution)
    int ret = system("echo Hello from system()");
    printf("system() returned: %d\n", ret);

    return 0;  // Equivalent to exit(0)
}
FunctionDescription
exit(code)Normal termination: flushes buffers, calls atexit handlers
_exit(code)Immediate termination: no cleanup
abort()Abnormal termination: raises SIGABRT
atexit(fn)Register a function to call at exit (LIFO order)
system(cmd)Execute a shell command
getenv / _putenv_sGet/set environment variables

Build docs developers (and LLMs) love