How to improve code around flawfinder memset warning?

388 Views Asked by At

In my code, all calls to memset appear as warnings with the flawfinder tool.

In the simplest case it could boil down to the equivalent to

    float f1;
    float f2;
    void* p1 = &f1;
    void* p2 = &f2;
    memcpy(p1, p2, sizeof(float));

The message is

./file.cpp:10:  [2] (buffer) memcpy:
  Does not check for buffer overflows when copying to destination (CWE-120).
  Make sure destination can always hold the source data.

I absolutely understand that this could be replaced by a simple copy, this is just a simplified example. I also understand what are the potential problems with using memcpy and buffer overrun.

The question is what is exactly flawfinder asking me to do here?

Perhaps something like adding an assert? (this didn't suppress the warning)

    assert( sizeof(*p1) == sizeof(*p2) );
    memcpy(p1, p2, sizeof(float));

Or is it just telling me just don't use memset?

I am programming in C++, but I am pretty sure the question and the solution is common to both C and C++ languages.

1

There are 1 best solutions below

4
Giel On
errno_t  err = memcpy_s(dest, dsize, src, cnt);

that should be the 'safe' version which hopefully satisfies flawfinder