【问题标题】:C++ stringstream segmentation faultC++ 字符串流分段错误
【发布时间】:2011-11-23 13:21:38
【问题描述】:

我写了这个程序:

#include <sstream>
#include <math.h>
#include <string>
#include <vector>
using namespace std;

double distance(vector<double> *, vector<double> *, int);
const char* distances(vector<vector<double>* >, int);

double distance(vector<double> a, vector<double> b){
    double result = 0, di;
    for(int i=0;i<a.size();i++){
        di = a[i] - b[i];
        result += di*di;
    }
    return sqrt(result);
}

const char* distances(vector<vector<double>* > vectors, int accuracy=1){
    stringstream graphstr;
    graphstr << "strict graph {\n";
    for(int i=0; i<vectors.size();i++){
        int j=i+1;
        while(j<vectors.size()){
            graphstr << "\t" << i << " -- " << j << "\t [len=" << distance(vectors[i],vectors[j]) << "];\n";
            j+=accuracy;
        }
    }
    graphstr << "}\n";
    return graphstr.str().c_str();
}

当vectors.size() 大于 70 时,它会给我一个分段错误。有什么问题?

当我不向graphstr 添加新的刺时,没关系。

【问题讨论】:

  • 您是否尝试在启用所有警告和调试信息的情况下编译您的代码(即 Linux 上的 g++ -Wall -g)?然后在其上使用调试器(即gdb 或其ddd Linux 上的 GUI 前端)!

标签: c++ segmentation-fault stringstream


【解决方案1】:

您正在返回指向在函数退出时被释放的字符串的指针。

【讨论】:

  • 比如返回std::string - graphstr.str()
  • 有效!谢谢!我不知道是什么问题。但是我想要一个 const char* 作为返回值,而我用 swig 做了一个 python 扩展,而 swig 从 const char* 制作了一个 PyString。但我用 typemap 解决了它:%typemap(out) (string) { $result = PyString_FromString($1.c_str()); }
  • 我对swig知之甚少,如何处理这取决于稍后将如何管理内存。希望你的方法是正确的:)
【解决方案2】:

试试这个

将您的返回值从 const char* 更改为 char* 和

 char* buff = new char[4096];
 strcpy(buff,graphstr.str().c_str(),graphstr.str().size());
 return buff;

记得释放使用delete返回的内存

【讨论】:

  • 他会忘记的,我建议更改返回类型和返回字符串(实际上,我 确实 已经推荐了:))
  • 我是一个诚实的人,不会立即面临被发现的危险 ;-)
猜你喜欢
  • 1970-01-01
  • 2017-09-07
  • 1970-01-01
  • 1970-01-01
  • 2012-11-14
  • 2012-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多