Tomer Attali
Tomer Attali

Reputation: 23

malloc a specific pointer from a array of pointers

To shorten, my issue is simply understanding why would this code:

int main() {
    typedef int* ASElement;
    int zero = 0;
    int one = 1;
    int two = 2;
    int three = 3;
    ASElement *elements = (int**)malloc(4 * sizeof(ASElement));
    *elements = (int*)malloc(4*sizeof(int));
    *(elements) = &zero;
    *(*(elements+1)) = one; //segementation fault here


    printf("%d", *(*(elements+1)));



    return 0;
}

not work?

Upvotes: 0

Views: 79

Answers (1)

Pascal Cuoq
Pascal Cuoq

Reputation: 80276

Your program, as written, uses the contents at address elements+1 uninitialized when it does *(elements+1). You have never written at that address before, and it is inside a block allocated by malloc, so the value it contains is indeterminate and you are not allowed to use this value.

The crash you observed can be explained by the fact that when you executed the program, the contents of that memory location did not form a valid pointer. Perhaps the contents were zeroes, perhaps a number that did not happen to be a valid address for your program. You were lucky: the program might not have crashed.

Maybe you intended to write:

*(elements+1) = &one;

https://taas.trust-in-soft.com/tsnippet/t/cb539105

Upvotes: 2

Related Questions