【发布时间】:2017-07-10 16:16:50
【问题描述】:
我有一个旧的 C 代码,我正在更新为 C++。我已将所有数组(指向数组的指针)更改为向量。 此代码涉及多个文件。相关部分如下。
当我运行它时,我在第一次迭代计算 fn.cpp 中的 m[i] 时得到一个 Segmentation Fault 错误。如果我在语句之外定义 m,在它减速时,我会在 w[i] 上得到错误。 我不确定如何解决这个问题
在 main.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];
}
}
【问题讨论】:
-
您是否尝试过使用调试器单步执行您的代码?
-
做
m.at(i) = 1.0stackoverflow.com/questions/12204206/… -
只使用调试器
-
当我使用调试器检查代码时,它会停在 m[i] 或 w[i] 行(如果我声明了 vector
m(N_bath, 1.0))和在那条线上说分段错误,但没有别的 -
真的吗?没有堆栈跟踪可供探索?
标签: c++ vector segmentation-fault