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

adding element to an existing struct makes function crash on segmentation error

本文关键字:函数 分段 错误 崩溃 添加 元素 结构      更新时间:2023-10-16

我有以下结构:

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("1n");
        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 的额外双精度值会使上述函数在分段错误时崩溃。1,2,3 的输出如下所示:

211111...1

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

这是怎么回事?即使我从不修改匹配[i].second,也会发生这种情况。

如果更改结构定义,则应重新生成所有受影响的源文件(如果生成工具未自动执行此操作)。否则,您可能会将使用不同结构定义的模块链接在一起,这将导致令人困惑的错误(如您所见)。