我想实现一个简单的N体模拟并管理我想要使用链表来计算所有成对交互,以仅计算邻居之间的交互。这是代码:
#include <stdio.h>
#include <stdlib.h>
#define V 20
#define N_P 100
typedef struct _node{
int id;
struct _node *next;
} node;
typedef struct _particle{
double r[3];
node* n;
int coor[3];
} particle;
typedef struct _simulation_struct{
int N;
particle *system;
double L[3];
double s[3];
int nc[3];
node*** cell;
} simulation_struct;
simulation_struct *new_simulation(int N, double Lx, double Ly,double Lz,double R);
int main()
{
simulation_struct *simulation=new_simulation(N_P,V,V,V,2);
return 0;
}
simulation_struct *new_simulation(int N, double Lx, double Ly, double Lz,double R)
{
simulation_struct *simulation;
int i, j,k;
simulation =(simulation_struct*) malloc(1*sizeof(simulation));
simulation->N = N;
simulation->L[0] = Lx;
simulation->L[1] = Ly;
simulation->L[2] = Lz;
simulation->nc[0] = (int) (Lx/R)+1;
simulation->nc[1] = (int) (Lx/R)+1;
simulation->nc[2] = (int) (Lx/R)+1;
simulation->s[0] = Lx/simulation->nc[0];
simulation->s[1] = Ly/simulation->nc[1];
simulation->s[2] = Lz/simulation->nc[2];
simulation->system = (particle*)malloc(N*sizeof(particle));
simulation->cell =(node***) malloc ((simulation->nc[0])*sizeof(node **));
for (i=0; i < simulation->nc[0]; i++)
{
simulation->cell[i] = (node**)malloc((simulation >nc[1])*sizeof(node*));
for (j=0; j < simulation->nc[1];j++)
{
simulation->cell[i][j] = (node*)malloc((simulation->nc[2])*sizeof(node));
for (k=0; k < simulation->nc[2];k++)
{
simulation->cell[i][j][k].id = -1;
simulation->cell[i][j][k].next = NULL;
}
}
}
for (i=0; i < simulation->nc[0]; i++)
{
simulation->system[i].n = (node*)malloc(1*sizeof(node));
simulation->system[i].n->id = i;
}
return simulation;
}
我可以编译它,如果参数V和N_P很小(例如V = 10 N_P = 20),程序工作正常,但如果参数程序稍大一点我执行程序时发现分段错误错误。有人能告诉我我做错了吗?
提前致谢!!!!
答案 0 :(得分:0)
在
上运行调试器崩溃simulation->system = (particle*)malloc(N*sizeof(particle));
malloc
没有任何问题,所以问题必须来自之前的说明,看起来很好,好吧,如果之前的malloc
没问题。但事实并非如此:
simulation =(simulation_struct*) malloc(1*sizeof(simulation));
Bingo:sizeof(simulation)
应该是sizeof(simulation_struct)
或者结构没有足够的内存(simulation
是指针,大小为4或8,...):腐败的记忆。
修正:
simulation = malloc(sizeof(simulation_struct));
我测试了固定版本,它不再崩溃了。
注意:由于simulation_struct
很小,因此避免分配它会更好,并使用&amp;返回simulation_struct
:略微增加开销,但少一个malloc。
和C ++&amp; vector
或良好的矩阵模板也可以修复您的node ***
复杂结构,这通常会导致内存损坏/内存泄漏时尝试将其中一个复制到另一个中。