Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing const char * in constructor - will there be a memory leak?

Tags:

c++

Here is the code which I got:

struct ChoiceLine
{
    const char *prompt;
    ChoiceLine(const char *pr):
        prompt(pr)   //can this cause a memory leak?
    {
        ;
    }
};

...

ChoiceLine choiceLine("hello world");

So is it OK to initialize a const char* with another const char*?

PS: I know about std::string, which unfortunately does not fit my purposes.

like image 768
user3496846 Avatar asked Apr 04 '14 07:04

user3496846


2 Answers

Yes that's fine if a little unsafe: the memory associated with prompt is not owned by the class instance.

(In your particular case ChoiceLine choiceLine("hello world"); all will be well since the string literal will last the life of the program).

Hence it would have to be kept in scope for as long as the class instance was in scope.

If I were you I'd use a std::string as your class member and suffer a deep copy.

like image 113
Bathsheba Avatar answered Oct 25 '22 19:10

Bathsheba


There is no dynamic memory allocation, so there is no memory leak. Your data member just points to a string literal. It is the equivalent of doing this:

const char* c = "Hello, World!";
like image 36
juanchopanza Avatar answered Oct 25 '22 21:10

juanchopanza