Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allocate a memory to a given pointer to an array in C++

Tags:

c++

malloc

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.

like image 832
user550413 Avatar asked Jan 28 '26 06:01

user550413


1 Answers

You have to change your main like this:

X* a;     // create an uninitialized pointer
func(&a); // pass the address of that pointer to the function

And inside your function, do this:

void func(X** a){
   int size = 5;
   X* array = (X*)malloc(5*sizeof(X));
   //some writing to the array..
   *a = array; // change the value of the pointer to point to the array
               // you allocated
}

Note that in C++ the way to go would be to use an std::vector<X>:

std::vector<X> func() {
    std::vector<X> buffer(5);
    // do stuff with buffer
    return buffer;
}

std::vector<X> foo = func();

This would create a new vector inside the function and return a copy of that vector to the caller. Note that the copy would be optimized away.

like image 69
Björn Pollex Avatar answered Jan 30 '26 22:01

Björn Pollex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!