1
#include <iostream>

using namespace std;

int main()
{
    char * a = nullptr;
    
    {
        char * b = (char *) "hello";
        a = b;
    }
    
    cout << a << endl; // prints hello

    return 0;
}

I have the code above. I am having hard time understanding why the code doesnt crash. My reasoning is I expected a crash because I am passing pointer b to upper scope with pointer a and using it to cout. Since "hello" was created within b's scope and new keywords isnt used, I expected it to clean itself automatically like a variable in a scope. What am I thinking wrong??

Brian61354270
  • 8,690
  • 4
  • 21
  • 43
cs guy
  • 926
  • 2
  • 13
  • 33
  • 3
    There is nothing that would guarantee a "crash" in C++ – Eugene Sh. Apr 05 '21 at 15:54
  • @EugeneSh. How come? doesnt nullpointer deference gurantee a crash for example `MyClass *a = nullptr; a->someMethod();` – cs guy Apr 05 '21 at 16:02
  • No it doesn't. As long as the C++ standard does not tell "such and such shall result in crash". With a definition of "crash" (which apparently does not exist). – Eugene Sh. Apr 05 '21 at 16:03
  • 1
    @csguy To build off of what Eugene said, all the standard says is that dereferencing a null pointer is _undefined behavior_; there are not restrictions on what can or cannot happen. In fact, since undefined behavior is _impossible_ in a valid C++ program (since, tautologically, invoking UB makes your program invalid), the compiler is perfectly free to assume that statements which cause undefined behavior never occur. Your compiler may omit the call to `a->someMethod();` altogether, or it may plug its ears and compile that statement normally, which may end up "working" anyway. – Brian61354270 Apr 05 '21 at 16:16
  • 1
    @csguy see [What will happen when I call a member function on a NULL object pointer?](https://stackoverflow.com/questions/2533476/) – Remy Lebeau Apr 05 '21 at 18:38

1 Answers1

4

C-style string literal like "hello" has static storage duration; it exists in the life of the program. Then it's still valid for cout << a << endl; (while a is pointing to it) after the scope where b is defined.

String literals have static storage duration, and thus exist in memory for the life of the program.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • 1
    To add on, the string exists in file itself even before runtime. You can use a hex editor like hex workshop to see the string inside the file. You can modify the string and change the console output as well. – Niraeth Apr 05 '21 at 16:05