C++字符串流分段错误
我写了这个程序:
#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 添加新的字符串时,就可以了。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将返回指向在函数退出时释放的字符串的指针。
You're returning pointer to the string which gets deallocated at the exit from function.
试试这个
将返回值从 const char* 更改为 char* 并
记住使用 delete 释放返回的内存
Try this
Change your return value from const char* to char* and
Remember to free the memory returned using delete