The cout crashes my program. |
Well let's take a look at the code.
char *q;
So, q is a char pointer. What value does it have? You didn't set it yet, so it could be any value at all, thus it could be pointing anywhere in memory at all.
Now you set the value of the pointer to zero. The pointer is pointing at memory address zero. This is commonly known as a null pointer; it is a special memory address used to indicate that the pointer is deliberately not pointing at anything. In C++11, we now have the
nullptr keyword for this.
cout<<"q: "<<q<<endl;
Now, we pass the pointer to cout, using the << operator, which is cleverly overloaded to dela with char pointers. In this case, the result is: go to the address is points to, output that as a char, and output all the following addresses as a char until you get to a zero value, and then stop. You have thus passed a pointer that deliberately doesn't point at anything to cout. What happens when cout tries to read that memory address to output its contents as a char? Well, you can see for yourself in this case - a crash. I'd normally expect a segFault if you tried to dereference a null pointer yourself. Exactly what happens when you feed it to the << operator is not something I'd like to guess.
However, I would have expected it to deal with it elegantly. Using g++ 4.7.0 and the version of clang++ I have on my machine, it is dealt with elegantly without crashing - what compiler are you using?