#Unsafety of char* string

13 messages · Page 1 of 1 (latest)

plucky bay
#

Hi i'm reading Bjarne Stroustrup's book "The C++ programming language"
In chapter 7 i'm reading this snippet of code and paragraph

I don't understand the "It would obviously be unsafe to accept that assignment. It was (and is) a source of subtle errors, so
please don’t grumble too much if some old code fails to compile for this reason." part.

Why is it "obviously" unsafe apart from the fact that it is mutable ?

lyric reefBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

#

@plucky bay

Screenshots!

Your message appears to contain screenshots but no code. Please send code and error messages in text instead of screenshots if applicable!

grizzled musk
#

the mutability is the unsafe part

#

string literals are constants and are immutable

plucky bay
#

Oh so it was actually the fact that it is mutable that he meant as unsafe. is it because then anybody can change the string, eventually, let's say someone shrink it and another part of the code would try to read the string with the old content which would cause a crash due to out of bound access ?

grizzled musk
#

well attempting to modify the string will result in a segmentation fault. the program will crash

hot current
#

It's not about what happens if someone changes the string

#

They can't

#

String literals just cannot be modified. It's like trying to modify a pen's writing by assuming it's just a pencil

#

Except the ink is rigged to explode with friction or something... the analogy doesn't go that far

plucky bay
#

I think I kind of get what you mean, it's still kind of blurry in my head, maybe I'll have to experiment and dig more on that subject

#

!solved