Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Buggy code in "A Tour of C++" or non-compliant compiler?

Tags:

c++

c++11

g++

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) ++count;
      ++p;
   }
   return count;
}

The line while (p) did not sound right to me. I thought it should've been while (*p). However, not wanting to be too presumptuous, I tested the function with the following code.

int main(int argc, char** argv)
{
   char* p = argv[1];
   char x = argv[2][0];
   int count = count_x(p, x);

   std::cout
      << "Number of occurences of "
      << x << " in " << p << ": " << count << std::endl;
   return 0;
}

When I ran the program, it exited with Segmentation fault (core dumped). I was glad to see that error since the code did not look right to me to start with. However, now am curious. Is the code suggested in the book incorrect or is the compiler not C++11 compliant? The compiler is g++ (GCC) 4.7.3.

What makes the code of count_x strange is that the author, Bjarne Stroustrup, starts with the following implementation before finishing with the one I wrote first.

int count_x(char const* p, char x)
{
   if(p==nullptr) return 0;
   int count = 0;
   for (; p!=nullptr; ++p)
   {
      if (*p == x)
         ++count;
   }
   return count;
}

It made me think twice before concluding this is buggy code. Both versions appear to be buggy.

like image 623
R Sahu Avatar asked Mar 06 '14 22:03

R Sahu


1 Answers

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.

like image 174
Chris Drew Avatar answered Oct 14 '22 16:10

Chris Drew