memset() in C With Examples

The memset() function in C is used to set blocks of memory with a particular value.

In this article, we’ll have a look at how we can use this function in C programs.


Syntax of memset() in C

This function takes a memory location, taken to be a void* pointer. It then copies a byte (character) to the first n bytes pointed to by the memory location.

Since it updates the memory location, it also returns a pointer to that updated memory location, which is again a void* pointer.

Therefore, we can write its prototype as:

Here, mem_loc is the relevant memory location, and c is the unsigned character. It sets the first n bytes of mem_loc.

Since this deals with characters and therefore strings (char*), we get this function in the <string.h> header.

We will now write the complete import and the function call.

Let’s now look at examples regarding how we can use this function.

Using the memset() function in C

The above code snippet fills the first 5 characters of the string “Hello from JournalDev” with ‘H’. Let’s take a look at the output now:

As you can observe, the first 5 locations are indeed filled with ‘H’.

Now let’s take another example, where you want to fill elements from an offset location.

Output

This time, the last five characters are filled with ‘H’, since we specified the starting memory location address appropriately.


memset() vs calloc() vs naive iteration

A lot of times, we can use memset() to zero initialize arrays. Often, the performance of memset() is much faster than similar methods like calloc().

The below example illustrates this point while comparing the running time of both memset() and calloc() on a Linux Machine, using the <time.h> header file.

Output

As you can observe, memset() is almost thrice as fast as both calloc() and naive iteration, since it is optimized based on the architecture, beyond the C compiler!


Conclusion

We learned about how we can use memset() to set values of a memory location. We also verified that the performance of memset() is much better than the other functions since it is optimized as per the architecture.

References


By admin

Leave a Reply