LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   What is the existing period of character string in c++/c (https://www.linuxquestions.org/questions/linux-software-2/what-is-the-existing-period-of-character-string-in-c-c-808571/)

915086731 05-18-2010 06:31 AM

What is the existing period of character string in c++/c
 
Like the following c++ program, I define a pointer of char type in the class named "test". In the function init1(), str="hello1" , what is the existing period of "hello1". Whether the string "hello1" will be invalid if the function init1() exits ? then "str" point to the invalid field in memory. When will "hello1" and "hello2" be released by OS ?

Where is "hello1" stored in memory?
Code:

#include <iostream>
using namespace std;

class test{
    char *str;

public:
    void init1(){
        str = "hello1";              //Is "hello1" stored in stack?
    }
    void init2(){
        str = "hello2";
    }
    void display(){
        cout<< str << endl;
    }
};

int main(){
    test t1;
    t1.init1();
    t1.display();
    t1.init2();
    t1.display();
    return 0;
}

Code:

cout<< "hello everyone"
When will "hello everyone" be released?

Thanks !!

posixculprit 05-18-2010 07:45 AM

According to the ISO/IEC 9899:1999 C standard, second edition, section 6.4.5 "String literals", subsection "Semantics", second paragraph:

Quote:

In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals. The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. <...>


All times are GMT -5. The time now is 05:51 AM.