Using memset () in a structure that contains a floating point number

In a hybrid C / C ++ project, I found 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);
}

non stop Cppcheck to increase portability warning

Using memset () for a structure that contains a floating point number.

The message is true, but since the floating point number is declared double, it seems to be false, because in double (positive) zero value is encoded according to IEEE 754: [*]

0 00000000000 0000000000000000000000000000000000000000000000000000

So I would just suppress the warning and forget about it

void clear(ContainingDouble* p)
{
    // cppcheck-suppress memsetClassFloat
    memset(p, 0, sizeof *p);
}

But maybe the problem is really important for portability?

Addendum:

Win32. , . , , , , - :

#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: -

+4
4

? . , . , .

interjay C, . "" .

IEEE 754, FPU. (, ) , IEEE 754 ( ...).

, , . , , IEEE 754, , , , memset() double with zeroes is not .

, , , , .

, C 50 , , , , 8 , , ( ). .

:

memset(&obj,0,sizeof obj);
#ifndef __STDC_IEC_559__
    obj.dbl_val=0.0;
#endif

dbl_val - double obj. , undefined, , , .

+5

, . ( 30 + ) C, - , . , , (, BDC , ASCII, ), .

, IMO , , , - , - , , .

+4

, C - .

, ++. .

[basic.fundamental]

: float, double long double. [...] .

, memset - C, ++.

+3

Windows (Win32). , , , ( ) , IEEE 754.

-:

  • ZeroMemory macro, WinBase.h ( Windows.h), , .

  • Disable the Cppcheck portability alert right before this call.

In other words:

#include <windows.h>

// ...

void clear(SharedMem* p)
{
    // cppcheck-suppress memsetClassFloat
    ZeroMemory(p, sizeof *p);
}
+1
source

Source: https://habr.com/ru/post/1682926/


All Articles