Stack or Heap

Hi,

I would like to know in the following code if "myvalue" is allocated on the stack ?

1
2
  char** var = new char*[1];
  var[0]= "myvalue";


var[0] will be valid while var is not deleted ?

Should I do ? What is the difference ?

1
2
  char** var = new char*[1];
  var[0]= strdup("myvalue");


Thanks.
would like to know in the following code if "myvalue" is allocated on the stack ?

"myvalue" is a text constant. It's allocated in a read-only area of your executable image. It exists for the duration of your program execution.

var[0] will be valid while var is not deleted ?

Yes.

Should I do ? What is the difference ?

Second example takes more memory. You now have two instances of "myvalue" in memory. One in the text area and one on the heap. You will need to free var[0] when deleting var, or you will have a memory leak.

Forget about trying to dynamically allocate char arrays and use the std::string container.

A conforming C++ implementation would generate an error for this:
1
2
    char** var = new char*[1];
    var[0] = "myvalue"; // *** error 

http://coliru.stacked-crooked.com/a/4c188307a121f814

A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration. - IS


This is fine ( if the implementation has ::strdup() in <string.h> ) :
1
2
char** var = new char*[1];
var[0]= strdup("myvalue");


This is the canonical C++ way:
1
2
std::vector< std::string > var ;
var.push_back( "myvalue" ) ;
Topic archived. No new replies allowed.