Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c_str() == NULL not working

Tags:

c++

I was going through legacy code to fix a problem and found out that checking c_str in the following manner does not work. However if I change the comparison to string.empty() it works. So my problem is solved, but I am not sure why the c_str comparison does not work.Any idea why?
Thanks!
I am using - gcc version 4.1.2 20080704 (Red Hat 4.1.2-46).

#include <iostream>  
using namespace std;  
int main()
{
   string a="";
   if (a.c_str() == NULL)
   {
     cout <<"char says empty"<<endl;
   }
   if (a.empty())
  {
    cout << "string says empty"<<endl;
  } 
 }

The output is-
string says I am empty

like image 328
Shailesh Avatar asked Dec 06 '22 18:12

Shailesh


2 Answers

a is not null in this case. The string object has an internal pointer, which is not null, and that pointer is what c_str returns.

To verify this, try

printf("%zu\n", a.c_str());

and you will get a real address.

like image 163
Foo Bah Avatar answered Dec 29 '22 13:12

Foo Bah


A null terminated string is never NULL, it always points to valid memory with a null terminator. The empty string is just a single \0. Since c_str() is contracted to return a null terminated string it can never return NULL. The correct way to test for an empty string is indeed empty().

like image 39
David Heffernan Avatar answered Dec 29 '22 12:12

David Heffernan