Course contentsShow
← C
Lesson 855 of 1,21912. The Standard LibraryFree lesson

Setting memory blocks with `memset`

Setting memory blocks with memset

What you'll learn: How to efficiently fill a large block of memory with a specific value using a single function call.

The problem with manual loops

Imagine you have a large whiteboard (a buffer) that is covered in old scribbles. To start a new project, you need to wipe it completely clean. You could take a tiny eraser and scrub every square inch manually, but that takes time and effort. In C, writing a for loop to set every single index of an array to zero is the programming equivalent of that tiny eraser. While it works, it’s verbose and often slower than it needs to be.

The memset solution

The memset function (found in the <string.h> header) is your "giant squeegee." It is designed to fill a block of memory with a specific byte value as fast as possible. It is most commonly used to "zero out" structures or arrays to ensure they don't contain "garbage data" left over from previous operations.

The function takes three arguments:

  1. The destination: A pointer to the start of the memory block.
  2. The value: The byte you want to write (usually 0).
  3. The size: How many bytes you want to fill.

Seeing it in action

Here is how you use memset to quickly clear a buffer:

#include <stdio.h>
#include <string.h>

int main() {
    char buffer[10];

    // Fill the first 5 bytes with the character 'A'
    // 'A' has an integer value of 65
    memset(buffer, 'A', 5);

    // Fill the remaining 5 bytes with null terminators (0)
    memset(buffer + 5, 0, 5);

    // Results in: AAAAA followed by five zeros
    printf("Buffer starts with: %s\n", buffer);

    return 0;
}

Important constraints

It is vital to remember that memset works byte by byte. If you try to use memset to fill an array of integers with the number 100, you won't get what you expect. Because an int is typically 4 bytes, memset will put the value 100 into every individual byte, resulting in a garbled large number. For this reason, memset is almost exclusively used for setting memory to 0 or for working with char arrays (strings).

Key takeaway

Use memset as a high-speed tool to initialize or clear memory blocks, primarily when you need to set everything to zero.