Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers's pointer c++ char initialization

I'm with a doubt In initialization of this in C++:

char** A_Function()
{
    char** charList = new char*[2];
    charList[0] = "abcde";
    charList[1] = "fghij";
    return charList;
}

There's no problem "on compiling this code", but I'm not sure about the behaviour.

1 - the char list: char* is on heap ok? 2 - the charList[n_position] is on heap or stack?

I don't understand what char*[2] realy means, does it mean: Its a static array that have on each of its element a pointer to a char?

If it is static this array will be allocated on stack, so this array is a huge bug maker?

If I'm right, how to allocate it on heap?

like image 971
okami Avatar asked Apr 08 '26 07:04

okami


2 Answers

Maybe a picture would help:

alt text

When you return from the A_Function, charList gets destroyed, but the other two remain intact. Since you're returning the value of charList from A_Function there's no problem -- you're just going to have that same value held in a different variable, at least assuming you actually use the return value from A_Function (i.e., assign it to something).

If you don't keep that value, you have a memory leak -- you'll no longer have a pointer to the array of two pointers you allocated on the free store, so you won't be able to free them.

like image 67
Jerry Coffin Avatar answered Apr 09 '26 22:04

Jerry Coffin


The array of 2 pointers of char * type is allocated in dynamic memory (heap). Each element of the array is set to point to a string (to a string literal) stored in static memory. Static memory is neither heap nor stack. Objects in static memory live as long as the program runs. So, formally, there are no problems in your code.

However, it is not a good idea to point to string literals with char * pointers. String literals are non-modifiable, so const char * pointers would be much more appropriate in this case.

like image 32
AnT Avatar answered Apr 09 '26 22:04

AnT



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!