我的test.cpp包含以下代码。我用valgrind描述了它,valgrind显示错误。我错过了什么?
#include<string>
#include<cstring>
#include<iostream>
void TestString(std::string & str)
{
char * tmpBuff = new char[3];
tmpBuff[0] = 'f';
tmpBuff[1] = 'o';
tmpBuff[2] = 'o';
str = tmpBuff;
delete [] tmpBuff;
}
int main(int argc, char* argv[])
{
std::string test_string;
TestString(test_string);
std::cout<<test_string;
return 0;
}
的valgrind日志
==5026== Invalid read of size 1
==5026== at 0x4A07F64: strlen (mc_replace_strmem.c:403)
==5026== by 0x347E29E14B: std::string::operator=(char const*) (in /usr/lib64/libstdc++.so.6.0.13)
==5026== by 0x4009AD: TestString(std::string&) (test.cpp:11)
==5026== by 0x4009EC: main (test.cpp:18)
==5026== Address 0x4c22043 is 0 bytes after a block of size 3 alloc'd
==5026== at 0x4A07152: operator new[](unsigned long) (vg_replace_malloc.c:363)
==5026== by 0x400979: TestString(std::string&) (test.cpp:7)
==5026== by 0x4009EC: main (test.cpp:18)
答案 0 :(得分:3)
tmpBuff
缺少终止\0
。
它应包含4个字符:'f', 'o', 'o', '\0'
。
答案 1 :(得分:2)
尝试以下修复
void TestString(std::string & str)
{
char * tmpBuff = new char[4]; // <<<
tmpBuff[0] = 'f';
tmpBuff[1] = 'o';
tmpBuff[2] = 'o';
tmpBuff[3] = '\0'; // <<<
str = tmpBuff;
delete [] tmpBuff;
}
C风格的字符串需要终止\0
字符。
答案 2 :(得分:1)
您呼叫的std::string(const char*)
构造函数需要nul terminated string。您没有传递一个,因此结果是未定义的行为。构造函数将尝试读取,直到找到\0
。
所以,传递一个nul终止的字符串,一切都会好的。