如何解决由于c_str()而导致的Valgrind错误

时间:2020-07-02 22:17:10

标签: c++ string char constants std

我很想写这种代码:

const char* what() const noexcept override
         {
           //just an example of what I have
           int n=3;
             std::string str="Mtm matrix error: Dimension mismatch: "+ n.toString()
             const char* str2 = str.c_str();
             return str2;
         }

由于我使用了c_str

,因此如何不断从valgrind收到这些错误
 Invalid read of size 1
==22582==    at 0x4C30A56: __GI_mempcpy (/builddir/build/BUILD/valgrind-3.13.0/memcheck/../shared/vg_replace_strmem.c:1525)
==22582==    by 0x56CF964: _IO_file_xsputn@@GLIBC_2.2.5
==22582==    by 0x56C4741: fwrite
==22582==    by 0x4ECC8F4: std::basic_ostream<char, std::char_traits<char> >& std::__ostream_insert<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*, long)
==22582==    by 0x4ECCBF6: std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)
==22582==    by 0x402BA9: main
==22582==  Address 0x5a2429a is 26 bytes inside a block of size 111 free'd
==22582==    at 0x4C2B16D: operator delete(void*) (/builddir/build/BUILD/valgrind-3.13.0/coregrind/m_replacemalloc/vg_replace_malloc.c:576)
==22582==    by 0x4EF3B62: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()
==22582==    by 0x403ADE: mtm::Matrix<std::string>::DimensionMismatch::what() const
==22582==    by 0x402B9C: main
==22582==  Block was alloc'd at
==22582==    at 0x4C2A1E3: operator new(unsigned long) (/builddir/build/BUILD/valgrind-3.13.0/coregrind/m_replacemalloc/vg_replace_malloc.c:334)
==22582==    by 0x4EF3A18: std::string::_Rep::_S_create(unsigned long, unsigned long, std::allocator<char> const&)
==22582==    by 0x4EF462A: std::string::_Rep::_M_clone(std::allocator<char> const&, unsigned long)
==22582==    by 0x4EF46D3: std::string::reserve(unsigned long)
==22582==    by 0x4EF493E: std::string::append(char const*, unsigned long)
==22582==    by 0x401FF4: std::basic_string<char, std::char_traits<char>, std::allocator<char> > std::operator+<char, std::char_traits<char>, std::allocator<char> >(std::basic_string<char, std::char_traits<char>, std::allocator<char> >&&, char const*)

有人可以帮助我了解如何摆脱此错误,并且仍然将std::string转换为const char*

0 个答案:

没有答案