How to use memset ?

Feb 8, 2020 at 5:06am
I'm using memset in my program but it seems weird,
so I make a program to test it and the output wasn't
as same as I expected.
This is my code:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <cstring>

int main() {
    double a[1000];
    memset(a, 50, sizeof(a));
    for(int i = 0; i < 1000; i++) {
        std::cout << a[i] << std::endl;
    }
    return 0;
}


every line of the output is '6.7493e-67'.
So why?
Thanks a lot!
Last edited on Feb 8, 2020 at 5:15am
Feb 8, 2020 at 5:36am
memset() works on raw memory, so you filled the bytes of 'a' with the value 50, which in turn makes every double value in a be 0x3232323232323232, which who knows what that is.

If you want to fill 'a' with doubles having the value 50.0, you should use std::fill().
1
2
3
const size_t size = 1000;
double a[size];
std::fill(a, a + size, 50.0); //declared in <algorithm> 

Here's a couple examples of memset() being used on integer values:
1
2
3
4
5
6
char a[10];
memset(a, 50, sizeof(a));
std::cout << a[5] << std::endl; //will print 50
std::uint32_t b[10];
memset(b, 50, sizeof(b));
std::cout << b[5] << std::endl; //will print 842150450 
Note: 842150450 is 0x32323232 in decimal, or in mathematical terms:
842150450 = 50 * 2560 + 50 * 2561 + 50 * 2562 + 50 * 2563
Feb 8, 2020 at 6:12am
Thanks!
Feb 8, 2020 at 5:28pm
dig a little more...
the only generally useful thing you can really memset doubles to is zero, as all zero bytes = 0 in IEEE format etc. Its more or less the same for ints -- zero is useful and most other things are not usually. In both cases its probably a little slower because loading 8 bytes one by one into a double (or 64 bit int) is not as efficient as moving all 8 at one operation using the cpu's double copy to double hardware. Its been quite a while since I have felt any need to use it.
Feb 8, 2020 at 5:40pm
JSYK, not all C/C++ systems use IEEE formatted values for floats and doubles. (But I don’t recall — or believe — that any of them will fail to be 0.0 for all bytes = 0.)

In any case, the point is that you should prefer to initialize using the typed value over initializing with a raw memory wipe.
Topic archived. No new replies allowed.