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

后端 未结 2 921
走了就别回头了
走了就别回头了 2020-12-06 10:05

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         


        
相关标签:
2条回答
  • 2020-12-06 11:01

    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.

    0 讨论(0)
  • 2020-12-06 11:01

    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.

    0 讨论(0)
提交回复
热议问题