Memset Definition and use

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?


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.


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.


memset is a common way to set a memory region to 0 regardless of the data type. One can say that memset doesn't care about the data type and just sets all bytes to zero.

IMHO in C++ one should avoid doing memset when possible since it circumvents the type safety that C++ provides, instead one should use constructor or initialization as means of initializing. memset done on a class instance may also destroy something unintentionally:

e.g.

class A
{
public:
  shared_ptr<char*> _p;
};

a memset on an instance of the above would not do a reference counter decrement properly.


I guess that serv_addr is some local or global variable of some struct type -perhaps struct sockaddr- (or maybe a class).

&serv_addr is taking the address of that variable. It is a valid address, given as first argument to memset. The second argument to memset is the byte to be used for filling (zero byte). The last argument to memset is the size, in bytes, of that memory zone to fill, which is the size of that serv_addr variable in your example.

So this call to memset clears a global or local variable serv_addr containing some struct.

In practice, the GCC compiler, when it is optimizing, will generate clever code for that, usually unrolling and inlining it (actually, it is often a builtin, so GCC can generate very clever code for it).