2

I have a simple program:

#include "stdafx.h"
#include <iostream>
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
    unsigned short a;
    cin >> a;
    cout << a;
    return 0;
}

When I input a number larger than 65535 (an overflow number), I always receive 52428 as the output. When I input a number smaller than 0 (an underflow number), the output is as expected (for example: the input -1 will have the output 65535).

I am using Visual Studio 2013 Ultimate, my friend is also using Visual Studio 2010 to compile this program and we both have the same result as above.

So what is exactly going on with the numbers larger than 65535 (the overflow numbers)?

Thanks in advance.


Hello, I found two other topics may help you out:

How does an uninitiliazed variable get a garbage value?

garbage values in C/C++

Thank you all of you for answering my question.

Community
  • 1
  • 1
ntvy95
  • 193
  • 1
  • 2
  • 10
  • 1
    Try initializing `a`, e.g. with 0, and see if the output looks familiar in that case. – molbdnilo Nov 29 '13 at 07:31
  • @molbdnilo I took a try and if I initialize a with value 10, the output is also 10 despite of whatever input is. – ntvy95 Nov 29 '13 at 15:16

2 Answers2

3

52428 is CCCC in hex; it's likely that it's using debug memory for the value. If you compile and run with the Release configuration you may get different results since it's truly uninitialised.

congusbongus
  • 13,359
  • 7
  • 71
  • 99
  • What do you mean by debug memory? – ntvy95 Nov 29 '13 at 07:06
  • 2
    In debug mode, MSVC fills uninitialized memory with special patterns. "CCCC" is one of them, but IIRC "FEEE" and "CDCD" are also used. – MSalters Nov 29 '13 at 07:34
  • @MSalters: But that doesn't happen to the underflow? – ntvy95 Nov 29 '13 at 15:15
  • It happens _before_ the read, regardless of what the read will later do. Problem is, if the read fails, the memory **remains** uninitialized. – MSalters Nov 30 '13 at 00:45
  • @MSalters: "before the read", you mean before the code line "cin >> a;" (or something's like that) being excuted? "If the read fails", then if inputing an overflow number is considered to make the read failed, so why inputing an underflow number is not considered to make the read failed? Sorry for my bad English. – ntvy95 Nov 30 '13 at 05:38
  • Yes, that's indeed what I meant. I don't know the exact details what is considered valid input for `operator>>(istream&, unsigned short&)`. – MSalters Nov 30 '13 at 12:39
2

It is better to check correctness of input this way:

std::cin >> a;
if (std::cin.fail())
  std::cout << "Error!\n";
else
  std::cout << "Valid.\n";
Ilya
  • 4,583
  • 4
  • 26
  • 51