0

Running the following code via the visual studio debugger executes successfully. The "count" variable will be default initialized to 0.

If I run via the command line, i get random behaviour and my EXPECT_EQ( ... ) fails.

size_t expectedCount = actual.length() - expected.length();
position += 12;
size_t count;
for (size_t i = position ; i < actual.length(); ++i) {
    if (actual.at(i) == 'a')
        ++count;
}

EXPECT_EQ(expectedCount , count);

I'm assuming this is because Visual studio gives me a clean stack (everything is 0) whereas the commandline has lingering garbage?

bgura
  • 860
  • 15
  • 33

2 Answers2

3

In a function scope, the syntax size_t count; will not initialize a variable. Use size_t count{};

For more info on initialization, see Variable initialization in C++.

Community
  • 1
  • 1
David Thomas
  • 778
  • 5
  • 10
  • You're assuming C++ not C. Is there a difference? – RamblinRose Jun 18 '16 at 04:31
  • 1
    ANSI C99 will initialize auto scope (function scope, non-static, non-thread-local) variables to an "indeterminate" value (garbage) in the absence of an initializer expression. Reference [ISO/IEC 9899:TC3](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf) See section 6.7.8 paragraph 10. _If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate._ – David Thomas Jun 21 '16 at 18:48
1

Your Debug build may be setting count to 0 due to the nature of that build configuration but not in Release build. You need to initialize count to zero. Always initialize variables.

RamblinRose
  • 4,883
  • 2
  • 21
  • 33