C memset() Function Explained with Examples (Beginner-Friendly Guide)

Hello, this is BlockDMask.

Today, we will learn about one of the most essential memory manipulation functions in C and C++: memset(). It is commonly used for array initialization and filling memory blocks with a specific value.

Table of Contents



✅ 1. What is memset()?

The memset() function allows you to fill a memory block with a specific value for a specified size (in bytes). The name is very intuitive: memory + set → set memory.

Here’s the function prototype:

void* memset(void* ptr, int value, size_t num);
  • ptr: Pointer to the start of the memory block to fill
  • value: The value to fill with (automatically cast to unsigned char)
  • num: Number of bytes to fill

Even though value is declared as int, internally it stores only 1 byte of data (unsigned char). So, characters like 'A' or numbers like 65 work the same.

Typically, we calculate the size using length * sizeof(datatype) format.

The function returns ptr on success. The header files required: <string.h> or <memory.h> (both work).

Simple usage example:

char buffer[] = "blockdmask";
memset(buffer, 'x', 4 * sizeof(char));
printf("%s", buffer);

This sets the first 4 characters of buffer to 'x'.



✅ 2. Example 1: Modify part of a string

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

int main(void)
{
    char sentence[] = "memset function example";
    memset(sentence, '*', 7 * sizeof(char));
    printf("%s\n", sentence);
    return 0;
}

Output:

*******function example

We replaced the first 7 characters with '*'. The rest of the string stays the same since we only modified the first part.

💡 In C, strings keep printing until they meet \0 (null terminator).



✅ 3. Example 2: Array initialization (for loop vs memset)

This is one of the most common uses of memset(): initializing integer arrays to zero.

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

void printArray(int* arr, int len)
{
    for (int i = 0; i < len; ++i)
        printf("%d ", arr[i]);
    printf("\n");
}

int main(void)
{
    // Initialize with for loop
    int arr1[10];
    for (int i = 0; i < 10; ++i)
        arr1[i] = 0;

    printf("for loop : ");
    printArray(arr1, 10);

    // Initialize with memset
    int arr2[10];
    memset(arr2, 0, 10 * sizeof(int));

    printf("memset    : ");
    printArray(arr2, 10);

    return 0;
}

Output:

for loop : 0 0 0 0 0 0 0 0 0 0
memset    : 0 0 0 0 0 0 0 0 0 0

✅ When setting all values to zero, both methods work identically. But memset() makes the code shorter and easier to maintain.



✅ 4. Example 3: Be careful when setting non-zero values

Now let’s look at a very common beginner mistake.

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

int main(void)
{
    int numbers[5];
    
    memset(numbers, 1, sizeof(numbers));

    for (int i = 0; i < 5; ++i)
        printf("%d ", numbers[i]);

    return 0;
}

Output (may vary by system but usually):

16843009 16843009 16843009 16843009 16843009

⚠ Why not simply 1?

  • memset() works byte-by-byte. Here, each byte is filled with 0x01.
  • An int has 4 bytes: 0x01010101 → which equals 16843009 in decimal.

✅ Rule of thumb:

  • memset() works safely with 0.
  • For non-zero integers, memset() is usually not safe!


✅ 5. Example 4: Quickly resetting structures

memset() is often used to clear structures (structs) before reuse:

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

typedef struct {
    int id;
    float score;
    char name[20];
} Student;

int main(void)
{
    Student s1 = { 1001, 95.2, "John" };

    printf("Before reset: id=%d, score=%.1f, name=%s\n", s1.id, s1.score, s1.name);

    // Reset all memory to 0
    memset(&s1, 0, sizeof(Student));

    printf("After reset : id=%d, score=%.1f, name=%s\n", s1.id, s1.score, s1.name);

    return 0;
}

Output:

Before reset: id=1001, score=95.2, name=John
After reset : id=0, score=0.0, name=

This is very useful when reusing structures or preventing garbage data.

⚠ Again: Only safe because we're filling with 0. If you want to set non-zero values, use loops or proper initialization logic.



That's everything you need to know about how to use memset() in C/C++ safely and effectively.
Thank you for reading!

Comments

Popular posts from this blog

Python split() Function: Usage and Examples

Privacy Policy for Android Apps

How to Write Comments in Python (Single-line, Multi-line, Shortcuts & Indentation Tips)