Course contentsShow
← C
Lesson 430 of 1,2196. Arrays and StringsFree lesson

Setting memory blocks with `memset`

Setting memory blocks with memset

What you'll learn: How to instantly fill an entire array or block of memory with a specific value using the memset function.

The "Paint Roller" of C

Imagine you have a long fence made of 100 wooden slats. If you want to paint the entire fence white, you could take a tiny brush and paint each slat one by one. In C, this is like using a for loop to assign a value to every index in an array. It works, but it’s tedious to write.

The memset function is like a giant paint roller. With one quick stroke, it covers the entire fence in a single color. It is a highly optimized function from the <string.h> library designed to fill a block of memory with a specific byte value as fast as possible.

How to use memset

To use it, you need to provide three pieces of information:

  1. Where: The pointer to the start of the memory block (usually your array name).
  2. What: The value you want to set (represented as an integer, though it sets memory byte-by-byte).
  3. How much: The total number of bytes to fill.

Here is how you might quickly "zero out" an array to ensure it contains no leftover junk data:

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

int main() {
    char buffer[10];

    // Fill the first 10 bytes of 'buffer' with the character 'A'
    memset(buffer, 'A', 10);

    // Make sure it's null-terminated so we can print it as a string
    buffer[9] = '\0';

    printf("Buffer contains: %s\n", buffer); // Outputs: AAAAAAAAA

    // Reset everything to zero (null characters)
    memset(buffer, 0, sizeof(buffer));

    return 0;
}

The Byte-Sized Catch

It is important to remember that memset works on bytes. This makes it perfect for char arrays (strings), where each element is exactly one byte. However, if you try to use memset to fill an int array with the number 1, you will get unexpected results. Because an integer is typically 4 bytes, memset will put a 1 in every single byte, creating a much larger number than you intended.

For this reason, memset is most commonly used for two things: filling strings with a specific character or resetting any type of array to all zeros.

Key takeaway

Use memset to rapidly fill a block of memory with a single value, but remember it operates byte-by-byte.