Alex Tape
Alex Tape

Reputation: 2291

Const Char* test() return String.c_Str() don't work properly

I m confused about this issue:

Const Char* Test() {
    String a = "anything";
    Return a.c_str();
}

Void Main() {
    Cout << Test(); // returns crap!
}

Anybody got an idea what i don't think of? This page is Not iPhone optimized ;-)

Upvotes: 2

Views: 332

Answers (3)

booiljoung
booiljoung

Reputation: 816

C language is stack based. String a in function Test() is allocated in stack.

const Char* Test() {
   std::string a = "anything";  // Allocated in stack based
   return a.c_str(); // A is freeing for return.
}

Void Main() {
    std::cout << Test(); // returns crap!
}

const char* Test(std::string *a) {
   *a = "anything";
   return a->c_str();
}

Void Main() {
    std::string a;
    std::cout << Test(&a);
}

OR

const Char* Test() {
   **static** std::string a = "anything";  // Allocated in data memory
   return a.c_str(); // data memory freed when application terminating.
}

Void Main() {
    std::cout << Test();
}

Upvotes: 1

Vijay
Vijay

Reputation: 67231

try with allocating the string on heap:

string *a=new string("anything");
return (*a).c_str();

Upvotes: 1

Roman Saveljev
Roman Saveljev

Reputation: 2594

String a is in automatic memory and it is destroyed when you return from Test(), so memory allocated for c_str is freed as well

Upvotes: 1

Related Questions