Why runtime error occur when we try to get the length of the NULL string?

cod*_*aty -3 c++ string pointers

Why the following code gives an error?

 // This a CPP Program 
#include <bits/stdc++.h> 
using namespace std; 
  

// Driver code 
 main() 
{ 
    string s=NULL;
    s.length();
}
Run Code Online (Sandbox Code Playgroud)

I know that a runtime error will occur because I am trying to get the length of the null string but I want to know why it is happening?

lub*_*bgr 6

You invoke the following overload of the std::string constructor (overload 5):

basic_string( const CharT* s, const Allocator& alloc = Allocator());
Run Code Online (Sandbox Code Playgroud)

And this is the explanation belonging to the constructor (emphasis mine):

Constructs the string with the contents initialized with a copy of the null-terminated character string pointed to by s. The length of the string is determined by the first null character. The behavior is undefined if [s, s + Traits::length(s)) is not a valid range (for example, if s is a null pointer).

Thus, you have undefined behavior at work. Referring back to your question, that outrules any further thoughts on "why it is happening", because UB can result in anything. You could wonder why it's specified as UB in the first place - this is because std::string shall by design work with C-style, zero-terminated strings (char*). However, NULL is not one. The empty, zero-terminated C-style string is e.g. "".