Menu

No longer catching memcpy on class in some cases?

2019-03-18
2019-03-19
  • Steve Hopkins

    Steve Hopkins - 2019-03-18

    Just upgraded from cppcheck v1.33 to v1.78. The code below was formerly flagged asUsing 'memcpy' on class, but is ignored with v1.78.
    test26.h:
    class foo_struct;
    namespace this_stuff
    {
    class FUBAR_struct
    {...}
    ...
    }
    test26.cpp:
    bool FUBAR_struct::getnext(foo_struct inp)
    {
    memcpy(inp, some_const, sizeof(foo_struct));

     
  • Daniel Marjamäki

    we still have the warning as far as I know.

    not sure.. we might have some new heuristic. maybe the class must have non-POD data or something.

     
  • Daniel Marjamäki

    Could you provide a better example code? When I test this code then latest cppcheck writes a warning:

    class Fred {
      std::string data;
    };
    
    void f(Fred *fred1, Fred *fred2) {
      memcpy(fred1, fred2, sizeof(Fred));
    }
    
     
  • Steve Hopkins

    Steve Hopkins - 2019-03-19

    OK. I reduced my offending file down to this, and I still get a 'memcpy' on class error with v1.33 but not with v1.78.
    test26.h:
    class ItemStruct;
    class CurrentStruct
    {
    bool getNext(ItemStruct *val);
    };

    test26.cpp:
    #include "test26.h"
    bool CurrentStruct::getNext(ItemStruct val)
    {
    ItemStruct
    bi = &(*next);
    memcpy(val, bi, sizeof(ItemStruct));
    return true;
    }

     
  • Paul Fultz

    Paul Fultz - 2019-03-19

    CurrentStruct is still considered a trivial(or POD-type) type and it can be default-constructed and copied. The following program compiles for me without an error:

    #include <type_traits>
    
    class ItemStruct;
    class CurrentStruct
    {
        bool getNext(ItemStruct *val);
    };
    
    int main() {
        static_assert(std::is_trivial<CurrentStruct>{}, "Its not trivial");
        static_assert(std::is_pod<CurrentStruct>{}, "Its not pod");
        // Default construct the object
        auto s1 = CurrentStruct{};
        // Copy the object
        auto s2 = s1;
    }
    

    So calling memcpy and memset on CurrentStruct is valid. Although, we could provide another diagnostic here. It could be suspicious to call memcpy or memset on an empty object. Within a generic template it may not be suspicious at all, so we need to be carefult to avoid FPs.

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.