Bug Buster 003: Can You Bust the Bug?

Bug Buster

This is our third bug for you to track down and eradicate. You can find the first bug here! How good are you at finding bugs in code? The following is a code snippet compiles fine. Unfortunately, it contains an error. Take a look at the code listing and see if you can find the error. To make it easier, several options are listed. One of the options is correct, while the others are not.

Can you find the error without looking at the choices?

Bug Buster #3

Here is the Bug Buster:

The code:

#include <algorithm>
#include <vector>
#include <array>
#include <iostream>

int main()
   std::array<int, 10> input =
   { 1, 2, 3, 3, 5,
     6, 7, 8, 9, 10 }; // 'random' input

   // copy odd numbers in new vector
   std::vector<int> odds(5); // new container for odd numbers
   auto it = std::copy_if(input.begin(),
      /*copy odd nbrs */   [](int i) { return i % 2; });

   // shrink container:
   odds.resize(std::distance(odds.begin(), it));

   for (const auto& x : odds)
      std::cout << x << std::endl;

   return 0;

Your choices:

The input array will throw an exception due to the duplicate data being added.
You can’t use a mod operator (%) in the embedded return statement.
This code will throw exception on the odds vector when the resize is attempted.
The odds array will throw an exception when the numbers are being added.
The program runs fine, but the odds array will end up with even numbers.
Nothing is wrong. The code works fine.

How quickly can you find the issue? Feel free to comment on how quick you were! We will be posting additional snippets over the coming weeks with additional bugs for you to bust. You can click to the next page to find the solution.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read