来自 for 循环的分段错误

Segmentation Fault from for loop

本文关键字:分段 错误 循环 for 来自      更新时间:2023-10-16

我有一个旧的C代码,我正在更新到C++。我已将所有数组(指向数组的指针(更改为向量。 此代码中涉及多个文件。相关部分如下。

当我运行它时,我在第一次迭代计算 fn.cpp 中的 m[i] 时出现分割错误错误。如果我在语句之外定义 m,在其减速时,我会得到 w[i] 上的错误。 我不确定如何解决这个问题

在主.cpp文件中:

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <complex>
#include "fn.h"
using namespace std;
#include <gsl/gsl_rng.h>

// ===========================
// Variables
// ===========================
double eta = 0.13;
double w_max = 3;
int N_bath = 60;
vector<double> m(N_bath);
vector<double> c(N_bath);
vector<double> w(N_bath);
void main(){
bath_para(eta, w_max);
}

在 fn.h 文件中:

#ifndef FUNCTIONS
#define FUNCTIONS
extern int N_bath;
extern vector<double> c;
extern vector<double> m;
extern vector<double> w;
#endif

在 fn.cpp 文件中:

#include   <stdlib.h>
#include   <stdio.h>
#include   <math.h>
#include   <iostream>
#include   <complex>
#include   <vector>
#include   "fn.h"
using namespace std;
void bath_para(double eta, double w_max){
double w_0;
w_0 = (1 - exp(-w_max))/N_bath;
for (int i = 0; i < N_bath; ++i){
m[i] = 1.0
w[i] = -log(1-(i+1)*w_0);
c[i] = sqrt(eta*w_0*m[i])*w[i];
}
}

您可能在其他地方有错误。使用以下 fn.h 代码不会产生任何错误(添加了 both_para 和命名空间的声明,我假设您错误地将其删除为无关紧要(:

#ifndef FUNCTIONS
#define FUNCTIONS
using namespace std;
extern int N_bath;
extern vector<double> c;
extern vector<double> m;
extern vector<double> w;
void bath_para(double eta, double w_max);
#endif