In a C/C++ hybrid project, I found some code that I could reduce to
#include <mem.h>
struct StructContainingDouble
{
double d;
/// other elements omitted
};
void clear(StructContainingDouble* p)
{
memset(p, 0, sizeof *p);
}
without stopping Cppcheck to raise the portability warning
Using memset() on struct which contains a floating point number.
The message is correct, but since the floating-point number is declared double, it seems to be false positive, because in double the (positive) zero value is encoded following the IEEE 754 standard:[*]
0 00000000000 0000000000000000000000000000000000000000000000000000
So I'd tend to simply suppress the warning and forget about it
void clear(ContainingDouble* p)
{
// cppcheck-suppress memsetClassFloat
memset(p, 0, sizeof *p);
}
But maybe there is really a portability issue here?
Addendum:
The actual code is based on the Win32 platform. The structure is used for managing access to shared memory, that's why constructors are useless. And it's not only one object of that structure that has to be zeroed, but an array of it that is embedded in another structure, something like this:
#include <mem.h>
struct Slot
{
double d;
// more members...
};
struct SharedMem
{
Slot slots[2048];
// more members...
};
void clear(SharedMem* p)
{
memset(p, 0, sizeof *p);
}
[*] from: Double-precision floating-point format - Wikipedia
memcpy
. – BrockieT val = T::zero
or*val_ptr = T::zero
. – Yttriumnullptr
doesn't have to zeroes either? But again I can't believe could be the case for a Windows machine.Zeroing can only (fully portably) initialize integer types. – Conniventmemset(p,0,2048*sizeof *p)
and be done with it? – ConniventSharedMem
has more members as well. And the warning would not go either. – Yttriumstd::calloc()
just returns zeroed memory? Has to be released bystd::free()
and the C++ crowd will have kittens... – Conniventstd::calloc()
is no option here. I already added that it's shared memory (it has to). – Yttriumclear()
performance (time, code space, memory space) would be compared to thismemset()
version. I suspect the differences would be moot in the larger coding picture. IMO 6.1 vs half-dozen of the other situation. – Buford