-3

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();
}

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?

crashmstr
  • 28,043
  • 9
  • 61
  • 79
codersaty
  • 23
  • 7
  • 2
    There is no such thing as the null string (unless by "null" you mean empty, which you don't). You're trying to initialize a string with a null pointer, which has undefined behaviour. – molbdnilo Nov 17 '20 at 12:56
  • 1
    My advice is to just use `string s;` The default constructor initializes the string already to an empty one. – drescherjm Nov 17 '20 at 12:57
  • 2
    This is not valid C++. You need `int` return type for `main`. – cigien Nov 17 '20 at 13:01
  • 2
    *"I know that a runtime error will occur..."* **Undefined behavior** does not require that. *"...because I am trying to get the length of the null string..."* That's is incorrect, the runtime error occurs before then. *"...but I want to know why it is happening?"* Because the program is invalid, because it has **undefined behavior**, because the code passes NULL to the string constructor. – Eljay Nov 17 '20 at 13:10

3 Answers3

6

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

basic_string( const CharT* s, const Allocator& alloc = Allocator());

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. "".

lubgr
  • 37,368
  • 3
  • 66
  • 117
3

Why the following code gives an error?

main must be declared to return int.

Also, to declare an empty string, make it string s; or string s="";

This would compile:

#include <iostream>
#include <string>

int main() 
{ 
    std::string s;
    std::cout << s.length() << '\n'; // prints 0
}

On a sidenote: Please read Why should I not #include <bits/stdc++.h>?

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
0

There is no such thing as the null string unless by "null" you mean empty, which you don't.

  • trying being constructive, adding knowledge, will also help those in the future that is looking for an answer. – Jaco Nov 17 '20 at 15:28