Blog Datasheets Home About me Clients My work Services Contact

G2Labs Grzegorz Grzęda

Understanding the memset() function in C

July 1, 2023

Understanding the memset() function in C

In the C programming language, the memset() function is a commonly used utility that allows you to set a specific value to a block of memory. This can be particularly useful when you need to initialize an array or a structure with a default value.

Function Parameters

The memset() function is defined with three parameters:

  1. ptr: This is the pointer to the start of the block of memory you want to fill.

  2. value: The value that you want to set for each byte of the specified memory. It’s important to note that this value is converted to an unsigned char to ensure that the filling is done byte by byte.

  3. num: The number of bytes to be set to the value.

Return Value

The function returns the same pointer ptr that was passed in, allowing for chained function calls.

Basic Usage Example

Here’s a simple example to demonstrate the use of memset():

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#include <string.h> // Required for memset

int main() {
    char buffer[100];

    // Initialize buffer with dashes
    memset(buffer, '-', 99);
    buffer[99] = '\0'; // Null-terminate the string

    // Now buffer contains 99 dashes followed by a null character
    return 0;
}

In this example, we fill a character buffer with 99 dashes and then null-terminate the string.

Extending the Examples

Let’s extend our examples to cover some additional use cases and corner cases:

Initializing an Array of Integers

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#include <string.h> // Required for memset

int main() {
    int numbers[100];

    // Initialize all elements to -1
    memset(numbers, -1, sizeof(numbers));

    return 0;
}

Clearing a Structure

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#include <string.h> // Required for memset

struct MyStruct {
    int id;
    float value;
    char name[100];
};

int main() {
    struct MyStruct myData;

    // Set all bytes of myData to 0
    memset(&myData, 0, sizeof(myData));

    return 0;
}

Corner Case: Using Non-Zero Values for Initialization

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#include <string.h> // Required for memset

int main() {
    char buffer[100];

    // Attempt to initialize buffer with 256 (0x100)
    // Only the least significant byte is used, so buffer is filled with 0's
    memset(buffer, 256, sizeof(buffer));

    return 0;
}

In this corner case, if you try to set buffer with 256, it won’t work as expected because memset() takes the value parameter as an int, but it actually uses only the least significant byte (LSB).

Custom Implementation Caution

While you can write your own implementation of memset(), like the one provided, it’s usually best to use the highly optimized standard library version. The standard memset() is designed to be efficient and reliable, leveraging platform-specific optimizations that may not be present in a custom implementation.

1
2
3
4
5
6
7
void *my_memset(void *ptr, int value, size_t num) {
    unsigned char *p = ptr;
    while (num--) {
        *p++ = (unsigned char)value;
    }
    return ptr;
}

Remember to include <string.h> and use the standard memset() in your actual projects for guaranteed performance and accuracy.


➡️ Code readability and maintainability tips for C and Python developers


⬅️ The memcpy() function in C: A beginner's guide


Go back to Posts.