C++字符串流分段错误

发布于 2024-12-17 15:39:26 字数 1118 浏览 1 评论 0原文

我写了这个程序:

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甚是思念 2024-12-24 15:39:26

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

You're returning pointer to the string which gets deallocated at the exit from function.

梦初启 2024-12-24 15:39:26

试试这个

将返回值从 const char* 更改为 char* 并

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

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文