【问题标题】:Buggy code in "A Tour of C++" or non-compliant compiler?“C++ 之旅”中的错误代码或不兼容的编译器?
【发布时间】:2014-04-09 20:26:29
【问题描述】:

我在“A Tour of C++”第 12 页看到了以下函数:

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

while (p) 对我来说听起来不太对劲。我认为应该是while (*p)。不过,不想太冒昧,我用下面的代码测试了这个函数。

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;
}

当我运行程序时,它以Segmentation fault (core dumped) 退出。我很高兴看到这个错误,因为代码在我看来并不合适。不过,现在很好奇。是书中建议的代码不正确还是编译器不兼容 C++11?编译器为 g++ (GCC) 4.7.3。

count_x 的代码之所以奇怪,是因为作者 Bjarne Stroustrup 从以下实现开始,然后才完成我首先编写的实现。

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;
}

这让我在断定这是错误代码之前三思而后行。两个版本似乎都有问题。

【问题讨论】:

  • 那段代码在我看来确实有问题。您是否有任何理由怀疑编译器不符合 C++11 标准? (另外,他们展示的代码绝对不是好的 C++ 代码——它应该使用std::stringstd::count 算法~)
  • @templatetypedef,我将很难将矛头指向 C++ 之父的书中的代码,并称其为 buggy,而没有确保有几次我不会失去理智:): )
  • @templatetypedef,该函数出现在本书的第一章“基础知识”中。他不会跳入std::stringstd::count 是有道理的。

标签: c++ c++11 g++


【解决方案1】:

这列在Errata for 2nd printing of A Tour of C++:

第 1 章:

pp 11-12: count_if() 的代码是错误的(没有按照它声称的那样做 to),但关于语言的观点是正确的。

现在第二次印刷中的代码如下:

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;
}

The C++ Programming Language (4th Edition) 中有一个类似的示例,A Tour of C++ 是基于该示例,但它没有这个错误。

【讨论】:

  • 有趣。代码为count_x,文本和勘误表为count_if()。你认为他们会在下一个版本中解决这个问题吗?
【解决方案2】:

gcc 在 4.7.3 有很好的兼容性,但是你必须用 -std=c++11 编译。 gnu webpage 上有图表。但是,是的,这不是标准的事情,该指针永远不会为 NULL,至少在它溢出之前不会,所以除非你已经分配了 char * 之上的所有内存,否则它将发生段错误。这只是一个错误。

【讨论】:

  • 如何告诉 C++ 之父他书中的代码有问题?
  • @RSahu 提交错误报告。
猜你喜欢
  • 1970-01-01
  • 2016-08-26
  • 1970-01-01
  • 2015-03-27
  • 1970-01-01
  • 1970-01-01
  • 2013-09-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多