0

I am trying to assign a const std::string variable to std::string variable.But getting some memory related error. code is like below:

#include <iostream>
#include <string>

using namespace std;
std::string sender1;

std::string fun()
{
      const std::string sender = "hi";
       sender1.assign(sender);
      
}

int main()
{
    fun();
    cout<<sender1<<endl;
    return 0;   
}
2

2 Answers 2

4

You've forgotten a return in fun. If you change that function like this:

std::string fun()
{
    const std::string sender = "hi";
    sender1.assign(sender);
    return sender;
}

then the code will compile and run fine.

Sign up to request clarification or add additional context in comments.

Comments

-1

I got the answer finally.

We need to declare a char * globally. Then using const_cast <char *> we can convert the constant string to char and assign it.

Example: in .h file:

char * abc;

in .cc file:

func()
{
 const std::string cde = "Hello";
 //now to use this constant string in another function,we use const cast and 
 //assign it to abc like below
 abc = const_cast <char *>(cde.c_str());
}

6 Comments

abc will point to data that is deallocated at the end of func() so it would be invalid to make use of it afterwards, see stackoverflow.com/questions/22330250/…
This doesn't do what you think it does. When the function returns the string variable cde will be destroyed. Then the pointer abc is left danging. This code is utterly broken.
but it worked for me. It doesn't create any dangling pointers. I haven't put the solution simply without working.
I'm sorry but the variable cde is constructed in the function and is destroyed when the function returns. The pointer is referring to the contents of a destroyed object. It might have "worked" in your simple test but the code definitely invokes undefined behavior and has a terrible bug.
You don't understand what you're talking about. The c_str() member function returns a pointer to the contents of the string (memory the string manages). After the string object is destroyed the pointer is no longer valid. It points inside a destroyed object or to memory that has been released back to the memory manager. The pointer assignment doesn't keep the data alive. It's a dangling pointer and the language standard says using that pointer is undefined behavior and your program is malformed. I'm not making this up, your code is a bug.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.