So, I want to better understand how string literals work in C ++. I am mostly concerned about situations where you assign the address of a string literal to a pointer and pass it. For example:
char* advice = "Don't stick your hands in the toaster.";
Now let's say that I just pass this line by copying pointers to the time the program runs. Of course, this is probably not a good idea, but I'm curious what is actually going on behind the scenes.
In another example, suppose we create a function that returns a string literal:
char* foo() {
Now let's say that this function is called very often, and the string literal is used only in half the cases when it called:
// situation
In the first situation, what actually happens? Is a string just created but not used and never freed?
In the second situation, the string will be maintained until the user finds the need for it? What happens when it is no longer needed ... will this memory be freed then (if nothing is pointed to this space)?
Don't get me wrong, I don't plan on using string literals like this. I plan to use a container to check my strings (maybe std :: string). I just want to know if these situations can cause problems for memory management or data corruption.
c ++ string memory-management string-literals
Tim leaf
source share