Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible for separately initialized string variables to overlap?

Tags:

c++

arrays

c++11

If I initialize several string(character array) variables in the following ways:

const char* myString1 = "string content 1";
const char* myString2 = "string content 2";

Since const char* is simply a pointer a specific char object, it does not contain any size or range information of the character array it is pointing to.

So, is it possible for two string literals to overlap each other? (The newly allocated overlap the old one)

By overlap, I mean the following behaviour;

// Continue from the code block above
std::cout << myString1 << std::endl;
std::cout << myString2 << std::endl;

It outputs

string costring content 2
string content 2

So the start of myString2 is somewhere in the middle of myString1. Because const char* does not "protect"("possess") a range of memory locations but only that one it points to, I do not see how C++ can prevent other string literals from "landing" on the memory locations of the older ones.

How does C++/compiler avoid such problem?

If I change const char* to const char[], is it still the same?

like image 590
Jaxon Avatar asked Jan 24 '23 04:01

Jaxon


2 Answers

Yes, string literals are allowed to overlap in general. From lex.string#9

... Whether all string-literals are distinct (that is, are stored in nonoverlapping objects) and whether successive evaluations of a string-literal yield the same or a different object is unspecified.

So it's up to the compiler to make a decision as to whether any string literals overlap in memory. You can write a program to check whether the string literals overlap, but since it's unspecified whether this happens, you may get different results every time you run the program.

like image 183
cigien Avatar answered Jan 26 '23 18:01

cigien


A string is required to end with a null character having a value of 0, and can't have such a character in the middle. So the only case where this is even possible is when two strings are equal from the start of one to the end of both. That is not the case in the example you gave, so those two particular strings would never overlap.

Edit: sorry, I didn't mean to mislead anybody. It's actually easy to put a null character in the middle of a string with \0. But most string handling functions, particularly those in the standard library, will treat that as the end of a string - so your strings will get truncated. Not very practical. Because of that the compiler won't try to construct such a string unless you explicitly ask it to.

like image 44
Mark Ransom Avatar answered Jan 26 '23 18:01

Mark Ransom