I’ve tried to allocate a memory this way:
main:
X** a;
func(a);
func:
func(X** a){
int size = 5;
X* array = (X*)malloc(5*sizeof(X));
//some writing to the array..
a = &array;
}
If using the debugger I see that when I am in the function func everything is okay = i can write to the array and a really points to the array but the moment I am back to the main I something changes and I can’t access the array through a (on the debugger it writes something like: Target request failed: Cannot access memory at address 0x909090c3 and so on).
Where is my mistake?
Note: It does compile but has a run-time problem if trying to access (print for example) the array in the main section.
Thanks.
You’re setting the local pointer
ato the address of the local pointerarray, when you want to set the target ofato the value ofarray:and call it as
It would be less confusing to return the pointer (i.e.
X * func()).Also, you’ve tagged this C++ not C, so you shouldn’t be using
malloc; use the standard containers, or if they don’t work for you, allocate usingnewand manage the memory with a smart pointer.