我有以下问题:我正在编写一个C++程序,它必须包装一个C库,所以当我与这个库交互时,我总是必须使用char*而不是std::string来执行所有操作。为了尽可能避免使用char*,我使用stringstreams进行格式化,例如:
#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)我做错了什么?
发布于 2012-07-18 16:45:14
const char *s = str.str().c_str();str()返回一个string对象。您可以使用c_str获取指向它的一些内部数据的指针,然后在行尾删除string对象。但是您仍然有一个指向已删除的内部字符串的指针。
你需要这样做-
std::string s = str.str();
const char* s = s.c_str()以确保字符串不会被删除。
https://stackoverflow.com/questions/11537367
复制相似问题