Friday, July 9, 2021

Use memset only with zero

Consider the following C++ definitions:

typedef struct {

int i;

double d[3];

} A_STRUCT

A_STRUCT s;

When I use memset(&s, 0, sizeof(s)), i and d values are set to zero as expected. When I use memset(&s, -1, sizeof(s)), I would expect all values to be -1 but on inspection you will see that they have strange values, in my case i was -1 but d values were -nan. When I use memset(&s, 1, sizeof(s)), I get 16843009 for i and 7.74...e-304 for d values.

Reason: The memset() function writes bytes, not words. So writing 1 to sizeof(int)*100 bytes writes 00000001 to every set of 8-bits.Thus, each integer in binary looks like the following:

0000 0001 0000 0001 0000 0001 0000 0001 (1 int = 4 bytes)

which in decimal is, exactly, 16843009..

memset doesn't only work with 0. It also works with all numbers with identically repeating byte pattern. Like for example ~0.

No comments:

Post a Comment