简体   繁体   中英

Why can't I construct a string with a NULL char* in C++?

In C++, why does the following code throw a runtime error? Could someone explain this for me?

char* p = NULL; 
string str(p); 

I tried this in VS2013 and Codeblocks, but both got a runtime error.

The constructor string::string(const char *) requires that the argument point to the first element of a null-terminated array of characters. You are violating that requirement.

For reference, [string.cons]:

 basic_string(const charT* s, const Allocator& a = Allocator());

Requires: s points to an array of at least traits::length(s) + 1 elements of charT .

(It is traits::length(s) ) that requires null termination of the array, see [char.traits.require].)

The constructor of the string class expects a pointer to a valid string. And a null-pointer isn't. But the run-time library might or might not check whether the given pointer is null. So, in one environment the code might simply crash and in another the run-time library might handle the error in another way, for example by throwing an exception.

Note the by

char* p = NULL;

you have not created an empty string, but a pointer with a value of zero, thus pointing to an illegal address. If you wanted to create a pointer to an empty string you should have written:

char* p = "";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM