Oleg
Oleg

Reputation: 1559

const char* vs const char[]

As far as I know , a string literal like "Hello"

is considered a char* in C and a const char* in C++ and for both languages the string literals are stored in read-only memory.(please correct me if I am wrong)

#include <stdio.h>

int main(void)
{
    const char* c1;
    const char* c2;

    {
        const char* source1 = "Hello";
        c1 = source1;

        const char source2[] = "Hi"; //isn't "Hi" in the same memory region as "Hello" ?
        c2 = source2;
    }

    printf("c1 = %s\n", c1); // prints Hello
    printf("c2 = %s\n", c2); // prints garbage

    return 0;
}

Why source1 and source2 behave differently ?(compiled with gcc -std=c11 -W -O3)

Upvotes: 23

Views: 29976

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

In this code snippet

{
 const char* source1 = "Hello";
 c1 = source1;

 const char source2[] = "Hi"; //isn't "Hi" in the same memory region as "Hello" ?
 c2 = source2;
}

source2 is a local character array of the code block that will be destroyed after exiting the block that is after the closing brace.

As for the character literal then it has static storage duration. So a pointer to the string literal will be valid after exiting the code block. The string literal will be alive opposite to the character array.

Take into account that in C the type of string literal "Hello" is char [6]. That is the type of any string literal is a non-const character array. Nevertheless you may not change string literals. Opposite to C in C++ character literals have types of const character arrays.

Upvotes: 15

Caleth
Caleth

Reputation: 62694

isn't "Hi" in the same memory region as "Hello"?

You are (subtly) mistaken. "Hello" on it's own is an expression that's not of type (const) char *, but of type (const) char[6]. char source2[] = "Hi"; is a statement that defines, declares and initialises a char [3] object. There is no const char * in sight. In a function scope that object has automatic storage duration.

In your usage, source2 ceases to exist at the following }, and makes c2 an invalid pointer. The use of c2 later is undefined.

Upvotes: 2

ForEveR
ForEveR

Reputation: 55887

const char* source1 = "Hello";

source1 is just pointer on memory-location, where Hello is defined.

const char source2[] = "Hi";

source2 is local variable of type array of chars and has another address, that string-literal Hi. After first } source2 will be destroyed and c2 will be pointed somewhere, but not on location of source2, so it's just undefined behaviour to dereference c2 after source2 is destroyed.

Upvotes: 9

Related Questions