Reputation: 3
I have a function which gets as a parameter a pointer to array,
e.g. int** segs
.
I need to allocate (in the function-body) memory for the array, which has size 100 for example.
My attempt was:
*segs=(int*)(malloc(100));
So far so good.
I put a value into *segs[0]
, and still everything is great.
But... when I try to reach *segs[1]
, I get an "invalid write of size 4" error from valgrind, which leads to seg-fault.
I have no idea why does that happen.
I tried to reach to *segs[2]
, but then I get even something weirder-
Error of uninitialised value of size 8.
Upvotes: 0
Views: 1184
Reputation: 206567
Due to operator precedence, *segs[N]
is treated as *(segs[N])
, which is ok when N
is equal to 0
. However, when you do the same thing using the index 1, things break since nothing has been allocated for segs[1]
For any index other than zero, you need to use (*segs)[N]
.
It will be easier to use a temporary pointer in the function.
int* ptr = (int*)(malloc(100));
*segs = ptr;
// and then
ptr[0] = ...; // Good
ptr[1] = ...; // Good
...
ptr[99] = ...; // Still good
Pass the pointer by reference.
void foo(int*& segs) { ... }
Use new
instead of malloc
to allocate memory.
segs = new int[100];
Better yet, use std::vector
insteady raw arrays.
void foo(std::vector<int>& segs) { ... }
Upvotes: 4