C null pointer with string literals

Using the ARM, C compiler, I can compile and run the following:

static char * myString = 0;

void myfunc(int x){

   if (x <= 0)
       myString = "Hello World";
   else 
       myString = "This is a different string with a different length";

}

int main(){

    myfunc(-1);
    printf("%s\n", myString);
    myfunc(2);
    printf("%s\n", myString);
}

Why does this work?

Shouldn't the pointer be a NULL pointer?

At a minimum, shouldn't a string literal be allocated to a read-only memory cell?

EDIT: its a C ++ compiler

EDIT2: Why does a string literal exist in a static scope after myfunc has gone out of scope? String literals not declared on stack? And when are they released?

Thank!

+3
source share
6 answers

The two ARE lines are allocated in read-only memory and are completely different. But you use the same pointer to point to each of them ... What not to understand?

, char* - . ( const const).

char* p = 0;
p = "Hello"; //OK
p = "Jo" //OK;
p[0] = 'X' //OOPS, now THIS is bad (undefined behavior)

:

, ( ), . .

+7

char const *MyString = 0;  

, const . - .

       .section        .rodata
.LC0:
        .string "Hello World"
        .align 8
.LC1:
        .string "This is a different string with a different length"
        .text

.

+3

" " , ( "" ). . .

, C.

.

+2

, , .

+1

. myfunc.

myfunc "Hello World". , , null.

( , ). C ++ char * (.. const char * ). char *, . -, .

String literals in C and C ++ have a static storage duration. So no, they are not allocated "on the stack." They are always allocated in static memory, which means that they live forever - while your program is running.

PS In order to answer your question in more detail, you must explain why on Earth you expect your pointer to remain blank.

PPS int main, not void main.

0
source

myString - a pointer variable, you intentionally set it to indicate the memory in which one of the two string constants is stored.

0
source

All Articles