简体   繁体   中英

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. what is the problem?

when I not adding new stings to graphstr it is OK.

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

Try this

Change your return value from const char* to char* and

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

Remember to free the memory returned using delete

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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