将元素添加到现有结构会导致函数在分段错误时崩溃

时间:2012-09-21 04:17:38

标签: c++ vector struct

我有以下结构:

struct FeatureMatch {
    int id1, id2;
    double score; 
};

在此函数调用时运行正常:

void ssdMatchFeatures(const FeatureSet &f1, const FeatureSet &f2, vector<FeatureMatch> &matches, double &totalScore) {
    int m = f1.size();
    int n = f2.size();
    matches.resize(15000);
    totalScore = 0;

    double d;
    double dBest;
    int idBest;
   printf("2");
    for (int i=0; i<m; i++) {
        dBest = 1e100;
        idBest = 0;

        for (int j=0; j<n; j++) {
            d = distanceSSD(f1[i].data, f2[j].data);

            if (d < dBest) {
        dBest = d;
        idBest = f2[j].id;
            }
        }
        printf("1\n");
        matches[i].id1 = f1[i].id;
        matches[i].id2 = idBest;
        matches[i].score = -dBest;
     //   matches[i].second=1;
        totalScore += matches[i].score;
    }

    printf("3");
}

但是,只要我通过添加新元素修改结构:

struct FeatureMatch {
    int id1, id2;
    double score, second; 
};

另一个名为second的double值会使上述函数在分段错误时崩溃。 1,2,3的输出显示如下:

21 1 1 1 1 。 。 。 1

但在它崩溃之前永远不会达到3。

这里发生了什么?即使我从不修改匹配[i]。第二,也会发生这种情况。

1 个答案:

答案 0 :(得分:1)

如果更改结构定义,则应该重建所有受影响的源文件(如果构建工具不会自动执行此操作)。否则,您可以将使用不同结构定义的模块链接在一起,这将导致混乱的错误(如您所见)。