I have a segmentation fault when affecting a value to a[1][0], i thought my mallocs were correct but maybe there're not..
int main() {
uint8_t **a;
a = malloc(sizeof(uint8_t) * 6);
*a = malloc(sizeof(uint8_t) * 2);
a[0][0] = 1; // WORKS
a[1][0] = 1; // DOES NOT WORK
}
Remember that the type of a
is "pointer to pointer to uint8_t
.
In your first malloc
, it looks like you want a
to point to an array of 6 uint8_t *
. So your sizeof
is wrong; you should do a = malloc(sizeof(uint8_t *) * 6)
.
Now a
points to (the first element of) an array of 6 pointers, which are a[0]
through a[5]
, each of which is uninitialized and probably doesn't point to anything useful.
In your second malloc
, you allocate enough memory to hold 2 uint8_t
, and set *a
, which is the same as a[0]
, to point to that memory. Note that a[1]
, ..., a[5]
still contain uninitialized pointers.
So accessing a[0][0]
is fine, since a[0]
does in fact point to valid memory.
a[1][0]
is not fine, because a[1]
doesn't point to valid memory. You never initialized a[1]
with anything.