提问人:7mf_s 提问时间:2/10/2023 更新时间:2/10/2023 访问量:63
为什么我得到双重释放或损坏(输出)或 C malloc 断言失败?
Why do I get either a double free or corruption (out) or a C malloc assertion failure?
问:
我正在为物理模拟编写代码,使用随机和确定性演化来演化初始状态的一些副本,在模拟的每个时间步长返回一些可观察值。我正在使用Armadillo(版本11.4.3)来处理线性代数和C++向量来分配内存。我在 Ubuntu 上运行它。代码是这样的:
vec class::run (bool verbose) const { // verbose = true => prints some trajectories and the exact result
vec observables(_num_timesteps);
int n_observable = 0;
// Allocating _N_ensemble copies of the initial state
std::vector<cx_vec> psi(_N_ensemble);
for (int i = 0; i <= _N_ensemble; ++i)
psi[i] = _initial_state;
// Exact solution and printing some of the trajectories
cx_mat rho_ex(_dim, _dim);
rho_ex = projector(_initial_state);
ofstream out_ex, traj;
if (verbose) {
out_ex.open("exact.txt");
traj.open("trajectories.txt");
}
for (double t = 0.; t <= _t_f; t += _dt) { // Time evolution
if (verbose) { // Prints and evolves the exact solution
out_ex << observable(rho_ex) << endl;
rho_ex = exact_evolution(rho_ex,t)
}
cx_mat rho(_dim, _dim, fill::zeros); // Average state
for (int i = 0; i < _N_ensemble; ++i) { // Cycle on the ensemble members
if (verbose && i < _N_traj_print) // Prints some trajectories
traj << observable(projector(psi[i])) << " ";
rho += projector(psi[i])/((double)_N_ensemble);
psi[i] = evolve(psi[i],t);
}
// Storing the observable
observables[n_observable] = observable(rho);
n_observable++;
if (verbose) traj << endl;
}
return observables;
}
所有以下划线开头的变量都应该是类的成员变量。
这个想法是执行时间。对于第一次执行,一切正常(只要足够大:如果一切正常,如果我得到 C malloc 断言失败;有关详细信息,请参阅以下内容)。run(verbose)
N
_N_ensemble
_N_ensemble=1000
_N_ensemble=100
问题在我第二次尝试第二次执行时出现。如果我用 运行它,它会正确地到达函数的末尾,但是当返回时,它会抛出错误verbose=false
observables
double free or corruption (out)
如果我用 运行它,它会在循环期间停止,给出 C malloc 断言失败:verbose=true
for
i
t=0
malloc.c:2617: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.
我不知道为什么它会抛出这些错误,因为所有内存分配都是由 C++ 向量处理的,而不是由我直接处理的,以及为什么它只发生在第二次运行期间。有谁知道为什么会这样?
有趣的是,如果我在 MacOS 上运行相同的代码,一切正常,我不会收到这些错误。
我尝试手动清除分配的向量,但没有任何变化。
答: 暂无答案
上一个:GCC 不熟悉内存分配的行为
评论