简体   繁体   中英

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. 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.

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. 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 .

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]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM