简体   繁体   中英

segmentation fault when using malloc and aliasing

The following code, which is distilled from my original code, causes segmentation fault. To farther investigation, I used a debugger and found that segmentation fault occurs at line of *pts[i][j]=... when i=0 and j=1.

When I replace *pts by a it works well. However, *pts is just an alias of a , so the behavior should be the same, I think. Could someone tell me why this error occurs?

#include<stdlib.h>

int main(){
    double*** a;
    int n = 3;
    int m = 3;
    int l = 3;

    a = (double***)malloc(n * sizeof(double**));
    double**** pts = &a;
    for(int i=0; i<n; i++){
        *pts[i] = (double**)malloc(m * sizeof(double*));
        for(int j=0; j<m; j++){
            *pts[i][j] = (double*)malloc(l * sizeof(double));
        }
    }
}

Variable subscription binds tighter than pointer dereference, so

*pts[i][j]

is parsed and executed as if you wrote

*(pts[i][j])

instead of

(*pts)[i][j]

First of all, I want to declare that pts[i] is the same as *(pts + i) , and *pts[i] is the same as **(pts + i) .

In this code, you should eighter use pts[i] or use *(pts +i) like:

#include<stdlib.h>

int main(){
    double*** a;
    int n = 3;
    int m = 3;
    int l = 3;

    a = (double***)malloc(n * sizeof(double**));
    double**** pts = &a;
    for(int i=0; i<n; i++){
        pts[i] = (double**)malloc(m * sizeof(double*)); // *(pts + i)
        for(int j=0; j<m; j++){
            pts[i][j] = (double*)malloc(l * sizeof(double)); // *(*(pts + i) + 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