I need to write in a variable allocated through a function. I found a lot of threads discussing this, such as Allocating a pointer by passing it through two functions and How to use realloc in a function in C, which helped me fixing some issues, but one remains and I can't find the cause.
Consider the following code:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
void foo(uint64_t** m)
{
        *m = realloc(*m, sizeof(uint64_t) * 4);
        *m[0] = (uint64_t)1;
        //*m[1] = (uint64_t)2; // create a segfault and crash right here, not at the print later
}
int main()
{
        uint64_t* memory = NULL;
        foo(&memory);
        for(int i = 0; i < 4; i++)
                printf("%d = %ld\n", i, memory[i]);
        return 0;
}
I send the address of memory to foo, which takes a double pointer as an argument so it can modify the variable. The realloc function need a size in bytes, so I make sure to ask for 4 * sizeof(uint64_t) to have enough space to write 4 64-bits int. (The realloc is needed, I don't need malloc).
I can then write in m[0] without issue. But if I write in m[1], the program crashes.
What did I do wrong here ?
