Ali1377's blog

By Ali1377, 11 years ago, In English

Hello! :)

One of my friends(kia.masster) submitted a problem with these two codes:

First submission

Second submission

The only difference is the "cerr" line. Why has this happened? :|

  • Vote: I like it
  • +9
  • Vote: I do not like it

»
11 years ago, # |
Rev. 2   Vote: I like it +12 Vote: I do not like it

Variable "s" was not initialized. This led to undefined behavior.

  • »
    »
    11 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Hello! :)

    1- It hasn't been initialized in second code also. 2- Where did you get this error? Be sure to compile it by GNU C++.

    • »
      »
      »
      11 years ago, # ^ |
      Rev. 2   Vote: I like it +10 Vote: I do not like it

      Hello there!

      Yes, it wasn't initialized in both codes. But I said it led to undefined behavior, not 100% wrong answer. If s is automatically initialized by 0 by compilator then your solution passes. If it is initialized by something else — bad luck:(.

      And I compiled this code by my Code:Blocks Gnu compiler. And the output was 0 on debug and 1 on release because of this problem.

»
11 years ago, # |
Rev. 2   Vote: I like it +2 Vote: I do not like it

s has a (pseudo) random value depending on the state of memory before using address X for variable s. The memory is not initialized at address X, so it still contains the value of the variable that was in that place before. So it depends on such strange things like calling printing routines. Printing routines use the memory, then mark it as free. But the memory is not usually cleared, it still contains the old values.

This regards to local variables. Global variables are initialized to 0.