views:

127

answers:

3

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?

+4  A: 

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.

AndreyT
huh, did not know that, @okami i apologize
aaa
I didn't know string literals were stored on static memory :-O
okami
+1  A: 

You can look at each of the individual pieces of new char*[2] to understand what it does:

new          dynamically allocate
new      [ ] an array
new      [2] of two
new char*[2] pointers to "char" objects

So, it dynamically allocates an array of two pointers to chars. It returns a pointer to the initial element of the allocated array (this is what the array form of new always returns). That pointer is stored in charList. charList is on the stack (it has automatic storage duration) and points to the dynamically allocated array, which is on the heap.

The two pointers in the dynamically allocated array, charList[0] and charList[1], are set to point to the string literals, "abcde" and "fghij", respectively. The string literals have static storage duration, so they exist for the entire time your program is running.

James McNellis
that was my confusion, if I do a copy of charList that was on stack after the method return, I couldn't ensure the charList was there like before.
okami
+6  A: 

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.

Jerry Coffin
+1 for the picture
Cedric H.