MEMSET()

The memset() is used to fill a block of memory with a specified byte value. It's often employed with C-style strings (character arrays) to clear or reset them by filling the array with null characters (\0). This effectively makes the string empty, as C-style strings are null-terminated. Additionally, this method is efficient for clearing buffers or strings before reuse, preventing leftover data or undefined behavior.

memset(string, 0, sizeof(string));

 * This sets all bytes in the string to 0 ('\0'), clearing the string completely.

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

int main() {
    // Declare and initialize a string
    char str[50] = "This will be cleared.";

    // Print the string before clearing
    printf("Before clear: %s\n", str);

    // Clear the string using memset
    memset(str, 0, sizeof(str));  // sizeof(str) returns the size of the array in bytes (50 in this case) - including the null character

    // Print the string after clearing
    printf("After clear: %s\n", str);

    return 0;
}

Last updated