Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the use of memset() return value?

Tags:

c++

c

memset

memset() is declared to return void* that is always the same value as the address passed into the function.

What's the use of the return value? Why does it not return void?

like image 312
sharptooth Avatar asked Dec 05 '12 09:12

sharptooth


People also ask

Why memset is used?

memset() is used to fill a block of memory with a particular value. The syntax of memset() function is as follows : // ptr ==> Starting address of memory to be filled // x ==> Value to be filled // n ==> Number of bytes to be filled starting // from ptr to be filled void *memset(void *ptr, int x, size_t n);

Where memset is defined?

memset() is built in standard string function that is defined in string header library string.

Does memset write to memory?

memset() will blindly write to the specified address for the number of specified bytes, regardless of what it might be overwriting. It is up to the programmer to ensure that only valid memory is written to.

Can we use memset in C++?

Memset() is a C++ function. It copies a single character for a specified number of times to an object. It is defined in <cstring> header file.


2 Answers

It may be used for call chaining like:

char a[200]; strcpy(memset(a, 0, 200), "bla"); 
like image 174
Juraj Blaho Avatar answered Sep 20 '22 19:09

Juraj Blaho


The signature is in line with all the other similar functions: memcpy(), strcpy() etc. I always thought this was done to enable one to chain calls to such functions, and to otherwise use such calls in expressions.

That said, I've never come across a real-world situation where I would feel compelled to use the return value in such a manner.

like image 29
NPE Avatar answered Sep 19 '22 19:09

NPE