Why does this cause access error reading null pointer?

J

Jim Langston

Microsoft Visual C++ .net 2003. I was just curious what numeric_limits for
std::string would give me so wrote this:

#include <iostream>
#include <string>
#include <limits>
int main()
{
std::cout << std::numeric_limits<std::string>::max() << '\n';
}

When I run it I get an access violation reading location 0x00000000
I couldn't quite figure out why however. Any thoughts?
 
O

Old Wolf

Microsoft Visual C++ .net 2003. I was just curious what
numeric_limits for std::string would give me so wrote this:

std::cout << std::numeric_limits<std::string>::max() << '\n';

When I run it I get an access violation reading location 0x00000000
I couldn't quite figure out why however. Any thoughts?

Well, the standard just says that using max()
on a type without numeric limits, is "not meaningful".

I don't know if this is licence to exit the program though.

BTW you can check if numeric_limits is defined for a
type, by reading the bool std::numeric_limits<T>::is_specialized.

Also, it is defined that non-fundamental standard types
(such as std::string) do not have specializations of
numerc_limits, so this property should always be
false for std::string.
 
K

Kai-Uwe Bux

Jim said:
Microsoft Visual C++ .net 2003. I was just curious what numeric_limits
for std::string would give me so wrote this:

#include <iostream>
#include <string>
#include <limits>
int main()
{
std::cout << std::numeric_limits<std::string>::max() << '\n';
}

When I run it I get an access violation reading location 0x00000000
I couldn't quite figure out why however. Any thoughts?

The default implementation of numeric_limits in your library may contain
code like this:


// default implementation
template < typename T >
struct numeric_limits {

static
T max ( void ) {
return ( T(0) );
}

// ...

};

In this case, the string is being constructed from the null pointer, which
yields UB.


Best

Kai-Uwe Bux
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,291
Messages
2,571,453
Members
48,132
Latest member
AnneHarpur

Latest Threads

Top