Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memset Definition and use

Tags:

c++

c

function

What's the usefulness of the function memset()?.

Definition: Sets the first num bytes of the block of memory pointed by ptr to the specified value (interpreted as an unsigned char).

Does this mean it hard codes a value in a memory address?

memset(&serv_addr,0,sizeof(serv_addr) is the example that I'm trying to understand.

Can someone please explain in a VERY simplified way?

like image 910
Brandon Ling Avatar asked Nov 10 '12 23:11

Brandon Ling


People also ask

What is the use of memset?

Description. The memset() function sets the first count bytes of dest to the value c. The value of c is converted to an unsigned character.

Where memset is defined?

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

Why do we use memset in C++?

memset in C++ In this section we will see what is the purpose of memset() function in C++. This function converts the value of a character to unsigned character and copies it into each of first n character of the object pointed by the given str[]. If the n is larger than string size, it will be undefined.

What is the use of Void memset?

The C library function void *memset(void *str, int c, size_t n) copies the character c (an unsigned char) to the first n characters of the string pointed to, by the argument str.


2 Answers

memset() is a very fast version of a relatively simple operation:

void* memset(void* b, int c, size_t len) {     char* p = (char*)b;     for (size_t i = 0; i != len; ++i) {         p[i] = c;     }     return b; } 

That is, memset(b, c, l) set the l bytes starting at address b to the value c. It just does it much faster than in the above implementation.

like image 167
Dietmar Kühl Avatar answered Sep 22 '22 09:09

Dietmar Kühl


memset() is usually used to initialise values. For example consider the following struct:

struct Size {     int width;     int height; } 

If you create one of these on the stack like so:

struct Size someSize; 

Then the values in that struct are going to be undefined. They might be zero, they might be whatever values happened to be there from when that portion of the stack was last used. So usually you would follow that line with:

memset(&someSize, 0, sizeof(someSize)); 

Of course it can be used for other scenarios, this is just one of them. Just think of it as a way to simply set a portion of memory to a certain value.

like image 32
mattjgalloway Avatar answered Sep 21 '22 09:09

mattjgalloway