0
votes

I was recently asked this question in an interview:

char* p = NULL;
cout << p << endl;
++p;
cout << p << endl;

I gave the answer that first cout will print 00000, next will print 00001. But when I checked it in visual studio, it gives an exception: First-chance exception at 0x009159F1 in StringFunctions.exe: 0xC0000005: Access violation reading location 0x00000000. Unhandled exception at 0x009159F1 in StringFunctions.exe: 0xC0000005: Access violation reading location 0x00000000.

But it works as expected for int, float etc. Could anybody explain this? Appreciate the help!

3
Undefined Behaviour. stackoverflow.com/a/19180731/1462718 and stackoverflow.com/a/394774/1462718 See the "Note that incrementing a pointer that contains a null pointer value strictly is undefined behavior".Brandon
This was not a duplicate of the proposed thread. While the OP is invoking UB by incrementing a null pointer, he is primarily concerned with how to print the address of a pointer.Ed S.

3 Answers

3
votes

The char* overload of std::cout::operator<< expects a null-terminated C-string. That's why it's trying to access the pointer.

To bypass this behavior, cast the pointer to void* first.

2
votes

The output stream knows that, when you pass a char*, you want to print a string. You passed an uninitialized pointer. It tried to read it as a C string... and, well, that invoked undefined behavior.

If you want to print an address cast to void* first, i.e., static_cast<void*>(p).

As an aside, NULL is not guaranteed to evaluate to 0 (in the all 0 bits sense). It is however guaranteed to compare equally to 0. Not the same thing. Also, your increment invokes UB as well.

0
votes

Sure, in simplest explanation, cout tries to deference the pointer and print the string because you passed a char pointer

The best way to understand this is following piece of code.

char *s = "hello";
cout << s+2 << endl; // Or &s[2]

It would output "llo" where as the first hunch would be something like "print address of first l"