开发者

c_str() == NULL not working

开发者 https://www.devze.com 2023-04-13 10:01 出处:网络
I was going through legacy code to fix a problem and found out that checking c_str in the following manner does no开发者_StackOverflowt work. However if I change the comparison to string.empty() it wo

I was going through legacy code to fix a problem and found out that checking c_str in the following manner does no开发者_StackOverflowt 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


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.


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().


At a guess, with an empty string, .c_str() is probably returning a non-NULL string to some memory, with the first byte set to '\0'. IOW, you're getting a zero-length string, not a null pointer.


std::string is not required to use NULL for storing empty strings.

On the other hand, c_str() is required to return a pointer to a null-terminated sequence of characters. The minimum memory size for this sequence is 1 (the required for the '\0'). So it cannot be NULL.

The right way to check if a std::string is empty is to call the empty() method.

You may also notice that on the following code:

char a[] = "";

The variable a is not NULL.


"" is not a null string, it is an empty string. In memory, it would contain a single character, \0. A null string, on the other hand, contains no characters: it doesn't even point to anything. Two completely different types of "empty", only one of which you test for.

0

精彩评论

暂无评论...
验证码 换一张
取 消