A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
memset fills a block of memory with a specified byte value. The most common use is zeroing: memset(&struct_var, 0, sizeof(struct_var)). This initializes every byte of a struct to zero, which sets integers to 0, floats to 0.0, pointers to NULL, and char arrays to empty strings. It is the C equivalent of a default constructor. It is also how you zero sensitive buffers before freeing them, as we covered in the heap inspection lesson.
#include <stdio.h>#include <string.h>typedef struct {int id;char name[32];double score;int *metadata;} Record;int main(void) {Record rec;memset(&rec, 0, sizeof(rec));printf("id: %d\n", rec.id);printf("name: \"%s\"\n", rec.name);printf("score: %.1f\n", rec.score);printf("metadata: %p\n", (void *)rec.metadata);return 0;}
Every field is zeroed. The pointer is NULL. The char array is an empty string. The int is 0. The double is 0.0. This works because the C standard guarantees that all-bits-zero represents 0 for integer types, 0.0 for floating-point types (on virtually all platforms), and NULL for pointer types. The memset idiom is the fastest way to get a clean struct.
#include <stdio.h>#include <string.h>int main(void) {unsigned char buffer[16];memset(buffer, 0xAA, sizeof(buffer));printf("Buffer: ");for (int i = 0; i < 16; i++) {printf("%02X ", buffer[i]);}printf("\n");return 0;}
memset takes an int but converts it to unsigned char before filling. Only the low byte is used. memset(buffer, 0x1234, n) fills with 0x34, not 0x1234. This trips up people who expect a multi-byte pattern. memset is a byte-fill function. For multi-byte patterns, use a loop.
Do not use memset to initialize an array of integers to a non-zero value. memset(arr, 1, sizeof(arr)) does not set each int to 1. It sets each byte to 1, producing 0x01010101 (16843009) on a 32-bit int system. Use a loop or designated initializers for non-zero integer arrays.
memset is the initialization workhorse. Zero a struct before populating it. Zero a buffer before use. Zero sensitive data before free. Three uses, one function, zero excuses for uninitialized memory bugs. Next: exit, for terminating a program with a status code.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.