简体   繁体   English

C ++字符串流分割错误

[英]C++ stringstream segmentation fault

I have writen this program: 我已经写了这个程序:

#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();
}

and when the vectors.size() is greather than 70 it gives me a segmentation fault. vectors.size()大于70时,会出现分段错误。 what is the problem? 问题是什么?

when I not adding new stings to graphstr it is OK. 当我不向graphstr添加新的graphstr时就可以了。

您将返回指向在函数出口处释放的字符串的指针。

Try this 尝试这个

Change your return value from const char* to char* and 将您的返回值从const char *更改为char *,然后

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

Remember to free the memory returned using delete 记住释放使用delete返回的内存

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM