There is a tendency among programmers to use memset() immediately after a malloc() or declaring a structure type variable. I find it amusing. Sometimes the structure is of considerable size and may not need memset() which should be called in a case by case basis. Let’s see.
example 1:
MyStruct_t a_struct; /* MyStruct has 5 members out of which we are setting only 2 below */
memset((void*) &a_struct, 0, sizeof(MyStruct_t)); /* required */
a_struct.var1 = x;
a_struct.var2 = y;
In this case memset() is required because we are selectively setting the values of some of the members of the structures and not all. So there is a chance of someone later accessing garbage value.
example 2:
MyStruct_t a_struct; /* MyStruct has 5 members out of which all are being set below */
memset((void*) &a_struct, 0, sizeof(MyStruct_t)); /* not required */
bytes = read(fd, &a_struct, sizeof(MyStruct_t));
if(bytes != sizeof(MyStruct_t)) { /* this check is a must */
/* log error and return */
}
Here memset() is not required as we are reading in the full size of the struct immediately. The check that follows read() takes care that correct number of bytes are read.