Is this .c_str() always safe ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Is this .c_str() always safe ?

Hi I have idea that we should be cautious with usage of c_str() function as it has some issued with lige time. But cant recall exact case Is below code always good or there will be some issue and might get undefined behavior ? https://code.sololearn.com/c9z6aDT58CMM/?ref=app

2nd Jan 2023, 9:38 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 Answers
+ 1
string::c_str() returns a string that is valid as long as the string variable is not mutated. So you have to be cautious while using it because you can't make any changes to the string variable while you are using the C-string returned by c_str(). Your code does not have any UB as the returned C-string is used for constructing (by copying) another 'string'. Here are 3 examples of UB https://code.sololearn.com/c91Ok9yE7JVx/?ref=app
2nd Jan 2023, 6:24 PM
XXX
XXX - avatar
0
Thanks
3rd Jan 2023, 4:07 AM
Ketan Lalcheta
Ketan Lalcheta - avatar