我有以下问题:我正在编写一个必须环绕 C 库的 C++ 程序,因此当我与库交互时,我总是必须使用char*
而不是std::string
所有操作。为了尽可能避免使用char*
,我使用字符串流进行格式化,例如:
#include <iostream>
#include <sstream>
#include <string.h>
#include <cstdlib>
using namespace std;
int main(int argc, char** argv)
{
ostringstream str;
str << argv[0] << "+" << "hello";
const char *s = str.str().c_str();
char *y = strdup(s);
// this I would give to a library function
cout << y << endl;
free(y);
return 0;
}
就输出而言,程序正确输出“./test+hello”。但是,valgrind 给了我很多类型的错误
==30350== Invalid read of size 1
==30350== at 0x402B858: __GI_strlen (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==30350== by 0x4213475: strdup (in /usr/lib/libc-2.16.so)
==30350== by 0x41B2604: (below main) (in /usr/lib/libc-2.16.so)
==30350== Address 0x4341274 is 12 bytes inside a block of size 25 free'd
==30350== at 0x4029F8C: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==30350== by 0x410387A: std::string::_Rep::_M_destroy(std::allocator<char> const&) (in /usr/lib/libstdc++.so.6.0.17)
==30350== by 0x41B2604: (below main) (in /usr/lib/libc-2.16.so)
我究竟做错了什么?