为什么我的构造函数退出时会引发分段错误?

时间:2019-05-30 00:01:04

标签: c++ segmentation-fault

我对C ++还是很陌生,发现很难深入研究内存管理之类的东西。现在,我正在尝试编写一些基本的解析器,但是构造函数由于存在分段错误而退出,并且找不到原因。

网络上的某个地方通知我,这是由于我自己以某种方式损坏了堆栈,但我还是很陌生,以了解问题的根源。

class Parser {
public:
    int *res, len = 0;
    string src;

// this len is the number of seps
Parser(const string &s, char t) : src(s) {
    int tmp = -1, flag = TRUE, tmps[MAX];
    while (flag) {
        tmp = s.find(t, tmp + 1);
        if (tmp == -1) {
            flag = FALSE;
        } else {
            tmps[len++] = tmp;  // len is now really the length
        }
    }
    res = (int *) malloc(len * sizeof(int));
    for (int i = 0; i < len; ++i) {
        *(res + i) = tmps[i];
    }
}

~Parser() {
    free(res);
    }
};

直接运行时,报告“进程以退出代码-1073741819(0xC0000005)完成”;在调试模式下,在指令“ mov%rax,(%rcx)”处引发“ SIGSEGV(分段故障)”。

1 个答案:

答案 0 :(得分:0)

感谢您的所有帮助,现在我已修复代码,在这里,我将为我的小解析器提供完整的解决方案,并附有用法。

#define MAX 99
#define TRUE 1
#define FALSE 0
#define INFEASIBLE -1
#define OVERFLOW -2

#include <iostream>
#include <vector>

using namespace std;

class Parser {
public:
vector<int> res;
int len;
string src;

Parser(string s, char t) : src(move(s)) {
    // churn a string and a seperator into a vector of ints
    int sep, next_sep, tmp;
    for (sep = -1, next_sep = 0; next_sep != -1; sep = next_sep) {
        next_sep = src.find(t, sep + 1);
        if (next_sep == -1) {
            res.push_back(stoi(src.substr(sep+1)));
        } else if (sep == -1) {
            res.push_back(stoi(src.substr(0, next_sep)));
        } else {
            res.push_back(stoi(src.substr(sep+1, next_sep - sep - 1)));
        }
    }
    len = res.size();
}
};


class TwoTierParser {
public:
vector<Parser> res;
int len;
string src;

TwoTierParser(string s, char x, char y) : src(move(s)) {
    // churn a string and two seperators into a vector of Parsers
    int sep, next_sep;
    for (sep = -1, next_sep = 0; next_sep != -1; sep = next_sep) {
        next_sep = src.find(x, sep + 1);
        if (next_sep == -1) {
            res.emplace_back(Parser(src.substr(sep+1), y));
        } else if (sep == -1) {
            res.emplace_back(Parser(src.substr(0, next_sep), y));
        } else {
            res.emplace_back(Parser(src.substr(sep+1, next_sep - sep - 1), y));
        }
    }
    len = res.size();
}
};


int main() {
char comma = ',', semicolon = ';';
string a;
//    cin >> a;
a = "1,2,3,4,5;6,7,8,9,10;11,12,13,14,15";
TwoTierParser parse(a, semicolon, comma);


int row = parse.len;
int col = parse.res[0].len;
int matrix[row][col];

for(int i=0; i<row; ++i){
    for(int j=0; j<col; ++j){
        matrix[i][j]=parse.res[i].res[j];
    }
}

for (int k = 0; k < row; ++k) {
    for (int i = 0; i < col; ++i) {
        cout<<matrix[k][i]<<" ";
    }
    cout<<"\n";
}
return 0;
}