C++ memset() is a function that copies a single character for a specified number of times to the given bytes of memory. It is useful for filling a number of bytes with a given value starting from a specific memory location.
Example:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
char str[5];
memset(str, 't', sizeof(str));
cout << str;
return 0;
}
In the above program, we declares a character array str of size 5, and then the memset function is used to initialize each element of the array with the character 't'.
Syntax of memset()
The memset() function is defined inside <cstring> header file.
C++
Parameters
- str[]: Pointer to the object to copy the character.
- ch: The character to copy. It can be a character, a normal value as well a Boolean value.
- n: Number of bytes to copy.
Return Value
- The memset() function returns str, the pointer to the destination string.
std::memset() converts the value ch to unsigned char and copies it into each of the first n characters of the object pointed to by str[]. If the object is not trivially-copyable (e.g., scalar, array, or a C-compatible struct), the behavior is undefined. If n is greater than the size of the object pointed to by str, the behaviour is undefined.
Examples of memset()
The following examples demonstrates the use of memset() functions in C++:
Character Array Initialization
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
char str[] = "geeksforgeeks";
// setting each byte of memory
// of str to 't' using memset
memset(str, 't', sizeof(str));
cout << str;
return 0;
}
In the above code, memset() function takes O(sizeof(str) time.
Initialize Integer Array
We can use memset() to set all values as 0 or -1 for integral data types also. It will not work if we use it to set as other values. The reason is simple, memset works byte by byte.
CPP
#include <bits/stdc++.h>
using namespace std;
int main() {
int a[5];
// memset() with value (0)
memset(a, 0, sizeof(a));
for (int i = 0; i < 5; i++)
cout << a[i] << " ";
cout << endl;
// memset() with value (1)
memset(a, -1, sizeof(a));
for (int i = 0; i < 5; i++)
cout << a[i] << " ";
cout << endl;
// memset() with value (5)
memset(a, 5, sizeof(a));
for (int i = 0; i < 5; i++)
cout << a[i] << " ";
}
Output0 0 0 0 0
-1 -1 -1 -1 -1
84215045 84215045 84215045 84215045 84215045
In the above program, we observe that using values like 0 or -1 with memset() works as expected. However, when setting a different value, such as 5, the result may not be as expected due to memset() operates at the byte level.
Initialize Boolean Array
CPP
#include <bits/stdc++.h>
using namespace std;
int main() {
bool prime[5];
memset(prime, true, sizeof(prime));
// If you print without using
// boolalpha it will print like this
for (int i = 0; i < 5; i++)
cout << prime[i] << " ";
cout << endl;
// If you use boolalpha it will
// print like this
for (int i = 0; i < 5; i++)
cout << boolalpha << prime[i] << " ";
return 0;
}
Output1 1 1 1 1
true true true true true
In the above program, When we print the array without using boolalpha, the output will be 1 1 1 1 1 because boolean values are represented as 1 for true and 0 for false by default. However, when we use boolalpha, the output will be true true true true true, as boolalpha changes the format of the output to display boolean values as the words true and false instead of 1 and 0.
Note: For boolean, the object must be of bool type for C++. Eg. bool arr[n];
Advantages of std::memset( )
- It is a one-line piece of code for initialization of large blocks of memory like array to a specific value, making it highly compact, fast and improving readability overall.
- memset() is a C function that works well in C++ as well, which makes it useful when working with codebases that involve both C and C++.
- By using memset(), you ensure that uninitialized memory is properly set, preventing potential issues with undefined or garbage values.
- The C++ memset() function aids the programmer in solving the misalignment issue. There are instances where you discover that the processor is having trouble with data alignment, which results in a programming mistake. The memcpy() and memcmp() methods in C++ are the best options in this situation.
Limitations of std::memset()
- memset() operates at the byte level, and its use is not type-safe. It treats the memory block as a sequence of bytes.
- For non-POD (Non - Plain Old Data) types in C++, such as classes with constructors, memset should be used with caution. Initializing such objects using memset can bypass constructors and lead to undefined behaviour. Instead, constructors should be used for initialization.
The memset() function is inherited from C. It is not very flexible when filling memory with different data types and value. The std::fill function is better alternative available in STL Algorithm library.
Similar Reads
std::memchr in C++
C++ offers various standard template library functions to be used. One of them is memchr() function which is used to search for the first occurrence of a character in a specified number of characters. memchr() is defined inside <cstring> header file. Syntax of memchr()const void* memchr( const
2 min read
std::memcmp() in C++
memcmp() function compares the first count bytes ( given number of characters ) of the memory pointed to by buf1 and buf2. memcmp() is a Standard Library function defined in <string.h> header file in C++. Syntaxint memcmp(const void *buf1, const void *buf2, size_t count);Parametersbuf1: Pointe
3 min read
memcpy() in C
The memcpy() function in C is defined in the <string.h> header is a part of the standard library in C. The memcpy() function is used to copy a block of memory from one location to another. Example: C#include <stdio.h> #include <string.h> // For memcpy int main() { // Initialize a v
2 min read
memmove() in C/C++
memmove() is used to copy a block of memory from a location to another. It is declared in string.h // Copies "numBytes" bytes from address "from" to address "to" void * memmove(void *to, const void *from, size_t numBytes); Below is a sample C program to show the working of memmove(). C /* A C progra
2 min read
Set in C++ STL
In C++, sets are associative container which stores unique elements in some sorted order. By default, it is sorted ascending order of the keys, but this can be changed as per requirement. It provides fast insertion, deletion and search operations.Example: C++#include <iostream> #include <se
7 min read
reverse() in C++ STL
In C++, the reverse() is a built-in function used to reverse the order of elements in the given range of elements. This range can be any STL container or an array. In this article, we will learn about reverse() function in C++.Letâs take a look at an example:C++#include <bits/stdc++.h> using n
3 min read
Multiset in C++ STL
In C++, multiset is an associative container similar to the set, but it can store multiple elements with same value. It is sorted in increasing order by default, but it can be changed to any desired order. It provides fast insertion, deletion and search operations.Example:C++#include <iostream
6 min read
set::size() in C++ STL
In C++, set::size() function is a built-in used to find the number of elements in the given set container. It is the member function of std::set class defined inside <set> header file. In this article, we will learn about the std::set::size() method in C++.Example:C++// C++ Program to illustra
2 min read
make_pair() in C++ STL
In C++, make_pair() is a standard library function used to construct a key-value pair from the given arguments. The type of the pair constructed is deduced automatically from the type of arguments. In this article, we will learn about make_pair() function in C++.Letâs take a quick look at a simple e
3 min read
iota() in C++
In C++, iota() is a library function used to fill a range of elements with increasing values starting from the given initial value. It assigns the starting value to the first element and then increments it once for the next element and so on.Let's take a look at an example:C++#include <bits/stdc+
3 min read