Reputation: 23
So will this code possibly cause a segfault because the pointer only is assigned the first memory address and the memory locations after it might outside of the usable range? Or will it allocate it by itself like an array of chars.
int main(){
char *final;
final = "This might cause a segfault. Especially if I am SUPPERRR LOOOOOOOOONNNNGG";
return 0;
}
Upvotes: 0
Views: 39
Reputation: 206577
Your use of the string literal is perfectly fine.
From the C++ Draft Standard (N3337):
2.14.5 String literals
8 Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n
const char
”, where n is the size of the string as defined below, and has static storage duration (3.7)....
12 Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation-defined. The effect of attempting to modify a string literal is undefined.
and
3.7.1 Static storage duration
1 All variables which do not have dynamic storage duration, do not have thread storage duration, and are not local have static storage duration. The storage for these entities shall last for the duration of the program
As long as you don't try to change the contents of the string literal through the pointer, there is no problem.
Upvotes: 1