Nagato
Nagato

Reputation: 87

How do constant strings work in C++

I have such a piece of code:

class temp {

private :
    char * name;
public :
    temp(char * temp_name){

        strcpy(name,temp_name);
    cout << "Created"<<name<<endl;

    }
    ~temp(){
        cout<< "Destoyed"<<name<<endl;

    }
};
int main() {
class temp person1("Jack");
class temp haha("Katy");
    return 0;
}

I was expecting to have 2 separate instances of class temp with separate names (Jack and Katy). With all Constructors and Destructors working fine. However, I got such a weird output:

CreatedJack

Process finished with exit code 11

I am pretty sure the problem is with constant string in the constructor temp(char * temp_name) but can't figure out what.

So my question is can you explain how, in terms of memory, is that constant string working and why I can't create 2 instances of class temp in this case?

Upvotes: 1

Views: 119

Answers (1)

user7860670
user7860670

Reputation: 37599

You need to allocate buffer of sufficient size to contain passed string data and initialize name with a pointer to this buffer. Right now you are dereferencing uninitialized pointer name getting Undefined Behavior.

Also this code won't even compile because you are trying to pass a string literal into constructor expecting a pointer to non-const qualified char. Most likely you are using Visual Studio that allowed such non-conformant behavior for quite a long time. Starting with VS2017 you should compile with /permissive- to enforce conformance. And change constructor signature to

temp(char const * const temp_name)

Upvotes: 5

Related Questions