A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
size_t is the unsigned integer type returned by sizeof and used by strlen, malloc, memcpy, fread, and dozens of other standard library functions. It is guaranteed to be large enough to represent the size of any object in bytes. On 32-bit systems it is typically 32 bits. On 64-bit systems, 64 bits. It is unsigned. It cannot represent negative values. This unsignedness creates comparison traps when you mix size_t with signed integers, and it is the source of a specific class of underflow bugs.
#include <stdio.h>#include <string.h>#include <stdlib.h>int main(void) {size_t s1 = sizeof(int);size_t s2 = strlen("hello");size_t s3 = sizeof(double[100]);printf("sizeof(int): %zu\n", s1);printf("strlen(\"hello\"): %zu\n", s2);printf("sizeof(double[100]): %zu\n", s3);printf("sizeof(size_t): %zu\n", sizeof(size_t));return 0;}
The %zu format specifier prints size_t values portably. Do not use %d or %ld. On some platforms, size_t is unsigned long. On others, it is unsigned long long. %zu handles both. The z length modifier tells printf the argument is size_t. This was introduced in C99.
#include <stdio.h>#include <string.h>int main(void) {const char *s = "Hi";size_t len = strlen(s);printf("len: %zu\n", len);printf("len - 5: %zu\n", len - 5);if (len - 5 > 0) {printf("len - 5 is positive (WRONG)\n");}return 0;}
2 - 5 in unsigned arithmetic wraps around to a huge number: SIZE_MAX - 2. The comparison len - 5 > 0 is true. The logic is broken. The fix: compare before subtracting. if (len > 5) { size_t diff = len - 5; ... }. Never subtract from an unsigned value without first verifying the result will not underflow.
#include <stdio.h>int main(void) {size_t len = 10;int i = -1;if (i < len) {printf("-1 < 10 is true\n");} else {printf("-1 < 10 is FALSE (unsigned conversion)\n");}printf("i as size_t: %zu\n", (size_t)i);return 0;}
When signed and unsigned meet in a comparison, the signed value is converted to unsigned. -1 becomes SIZE_MAX. SIZE_MAX < 10 is false. The comparison gives the mathematically wrong answer. This is the same signed-unsigned trap from the type casting lesson, applied to size_t. Use a signed type for loop counters that might be negative. Use size_t for sizes and counts that are always non-negative.
size_t is the language of sizes in C. Use it for array lengths, buffer sizes, and loop bounds over non-negative ranges. Respect its unsignedness. Never subtract without a bounds check. Never compare with a potentially negative signed value without casting deliberately. Standard library module complete. Next: structs and unions, where we build composite types and confront padding, alignment, and memory layout.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.