Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C null pointer with string literals

Using an ARM, C compiler, I can successfully 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 the very least, shouldn't the string literal by allocated in a read-only memory location?

EDIT: its a C++ compiler

EDIT2: Why does the string literal exist in static scope, after myfunc has gone out of scope? Are string literals not declared on the stack? And when do they get deallocated?

Thanks!

like image 795
J T Avatar asked Aug 05 '26 23:08

J T


1 Answers

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

Remember, char* is just a pointer. It is mutable (non-const).

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

After your edit:

No, string literals have static storage duration (unlike all other literals), they aren't created on stack . They will exist till program termination.

like image 128
Armen Tsirunyan Avatar answered Aug 08 '26 12:08

Armen Tsirunyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!