dynamic memory allocation
I had function call
hci_host_data_pkt_gen() in another function main_function(),
I want to know about the memory allocated(hci_host_data_pkt_arr = new()), when it would be destructed?
Would i get the values of hci_host_data_pkt_arr in main_function() or not??
1 2 3 4 5 6 7 8
|
unsigned char* hci_host_data_pkt_gen(int data_param_len)
{
hci_host_data_pkt_arr = new(nothrow) unsigned char [data_param_len];
hci_host_data_pkt_arr[0] = 0x02; //!PI
hci_host_data_pkt_arr[1] = con_handle_lsb; /
return hci_host_data_pkt_arr;
}
|
amitk3553 wrote: |
---|
I want to know about the memory allocated(hci_host_data_pkt_arr = new()), when it would be destructed? |
Whenever you
delete []
it.
amitk3553 wrote: |
---|
Would i get the values of hci_host_data_pkt_arr in main_function() or not?? |
Yes, providing that you assign the return value of the call to something in that function.
Not sure if it's intentional or not, but you haven't declared a variable for
hci_host_data_pkt_arr
within your function there.
Here's a generic example that might help:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
#include <iostream>
#include <new>
unsigned char* someFunction( int arr_size )
{
unsigned char* ret = new ( std::nothrow ) unsigned char [arr_size];
ret[0] = 'a';
ret[1] = 'z';
return ret;
}
int main( int argc, char* argv[] )
{
unsigned char* my_arr;
const unsigned int ARR_SIZE = 2;
my_arr = someFunction( ARR_SIZE );
for( int i = 0; i < ARR_SIZE; ++i )
std::cout << my_arr[i] << std::endl;
delete [] my_arr;
return 0;
}
|
It's not exactly safe (you could, for example, pass an array size of 1 to it) but it's for illustration purposes.
Last edited on
Topic archived. No new replies allowed.