I saw the following function in \"A Tour of C++\", page 12:
int count_x(char const* p, char x)
{
int count = 0;
while (p)
{
if (*p == x) ++cou
This is listed in the Errata for 2nd printing of A Tour of C++:
Chapter 1:
pp 11-12: The code for count_if() is wrong (doesn't do what it claims to), but the points made about the language are correct.
The code in the 2nd Printing now reads:
int count_x(char* p, char x)
// count the number of occurences of x in p[]
// p is assumed to point to a zero-terminated array of char (or to nothing)
{
if (p==nullptr) return 0;
int count = 0;
while(*p) {
if(*p==x)
++count;
++p;
}
return count;
}
There is a similar example in The C++ Programming Language (4th Edition) on which A Tour of C++ was based but it does not have this bug.
gcc has good compatibility at 4.7.3, but you have to compile with -std=c++11. There are charts on the gnu webpage. But yeah, that's not a standard thing, that pointer is just never going to be NULL, at least not until it overflows, so unless you've allocated all the memory above the char *, it's going to segfault. It's just a bug.