1

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!

  • Undefined Behaviour. http://stackoverflow.com/a/19180731/1462718 and http://stackoverflow.com/a/394774/1462718 See the "Note that incrementing a pointer that contains a null pointer value strictly is undefined behavior". – Brandon Mar 02 '15 at 05:31
  • 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. Mar 02 '15 at 19:16

3 Answers3

4

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.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
2

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.

Ed S.
  • 122,712
  • 22
  • 185
  • 265
  • Do you have any examples of situations where NULL is not defined as 0? People always say that, yet there is no logical reason to do it. – brettwhiteman Mar 02 '15 at 06:39
  • @Brett: I have a spec, as you do. That doesn't mean it won't work in practice, it only means that you shouldn't write code which counts on it if you can avoid it. – Ed S. Mar 02 '15 at 06:52
  • C++ these days recommends using the keyword, nullptr, rather than NULL or 0. – Alan Baljeu May 28 '18 at 16:40
0

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"

fkl
  • 5,412
  • 4
  • 28
  • 68