Menu

false positive memsetClass

Kevin Bro
2023-04-24
2023-04-24
  • Kevin Bro

    Kevin Bro - 2023-04-24

    template specialization is not considered

    #pragma once
    
    #include <cstdint>
    #include <cstring>
    #include <string>
    #include <type_traits>
    
    template<class T>
    class Dummy
    {
    public:
      bool setValue( uint8_t* buffer, uint16_t size ) ;
    
    private:
      T data = {};
    };
    
    template<class T>
    bool Dummy<T>::setValue( uint8_t* buffer, uint16_t size )
    {
      T newData{};
      std::memcpy( &newData, buffer, size );
      data = newData;
      return true;
    }
    
    template<>
    bool Dummy<std::string>::setValue( uint8_t* buffer, uint16_t size )
    {
      char* cstring = reinterpret_cast<char*>( buffer );
      std::string newData( cstring, size - 1 );
      data = newData;
      return true;
    }
    

    leads to

    <?xml version="1.0" encoding="UTF-8"?>
    <results version="2">
        <cppcheck version="2.10"/>
        <errors>
            <error id="memsetClass" severity="error" msg="Using &apos;memcpy&apos; on std::string." verbose="Using &apos;memcpy&apos; on std::string is unsafe, because constructor, destructor and copy operator calls are omitted. These are necessary for this non-POD type to ensure that a valid object is created." cwe="762" file0="Dummy/Dummy.cpp">
                <location file="Dummy\Dummy.hpp" line="22" column="8"/>
                <symbol>memcpy</symbol>
                <symbol>std::string</symbol>
            </error>
        </errors>
    </results>
    
     
  • CHR

    CHR - 2023-04-24

    Thanks for reporting, ticket is here: https://trac.cppcheck.net/ticket/11686

     

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.