[英]segmentation fault (core dumped) when dynamically allocating a 2d array
I am getting a segmentation fault (core dumped)
when using a 2d array that has been dynamically allocated.使用动态分配的二维数组时出现segmentation fault (core dumped)
。 My code is the followging:我的代码如下:
#define TMILKY 1e4
#define TABLE_SIZE 10000
struct func_params{
double *(pop)[3];
};
I want to allocate a 2d array of TABLE_SIZE rows and 3 columns.我想分配一个 TABLE_SIZE 行和 3 列的二维数组。
int main(int argc, char **argv){
struct func_params params;
double t=0;
int i=0;
params.pop[3] = malloc(sizeof(*params.pop[0]) * TABLE_SIZE);
if (params.pop == NULL) printf("population: allocation failed");
while (t<TMILKY){
params.pop[0][i]=0;
params.pop[1][i]=2;
params.population[2][i]=0;
printf("i %d t %e P %e B %e \n",i,t,params.population[0][i],params.population[1][i]);
t = t+100;
i++;
}
free(params.population[3]); /* deallocate the buffer */
return(0);
}
Could someone please help to spot my mistake...?有人可以帮助发现我的错误...?
params.pop[3]
is an out-of-range element. params.pop[3]
是一个超出范围的元素。 You must not read nor write anything there.你不能在那里读或写任何东西。
Instead of using that, you have to use malloc()
and free()
for each elements of params.pop
.而不是使用它,您必须对params.pop
的每个元素使用malloc()
和free()
。
Allocation:分配:
for (int j = 0; j < 3; j++) {
params.pop[j] = malloc(sizeof(*params.pop[j]) * TABLE_SIZE);
}
Freeing:释放:
for (int j = 0; j < 3; j++) {
free(params.pop[j]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.