0

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 ?

Katoptriss
  • 107
  • 6
  • Is crashing because you are reading uninitialized values from `memory[1]` to `memory[3]`, consider using `calloc` if you want to auto-initialize the data. – David Ranieri Nov 30 '21 at 13:37
  • @DavidRanieri No, even without the print, the program crashes right at the writing in m[1]. – Katoptriss Nov 30 '21 at 13:38
  • 3
    Yes, you also need `(*m)[1] = 2;` instead of `*m[1] = (uint64_t)2;` due to operator precedence. (Notice that you don't need the cast) – David Ranieri Nov 30 '21 at 13:40
  • @DavidRanieri Oh... so the [] operator has a priority on *. I see. Thank you for answering me. – Katoptriss Nov 30 '21 at 13:42

0 Answers0