Search code examples
c++cprogramming-languages

garbage values in C/C++


Possible Duplicate:
How an uninitialised variable gets a garbage value?

How are garbage values generated in C and C++ ? Does the compiler use some random number generation technique for generating garbage values?


Solution

  • If you mean the values of uninitialized variables, those aren't generated. They're just whatever garbage happened to be in that memory location.

    int *foo = new int;
    std::cout << *foo << std::endl;
    

    New returned a pointer to some address in memory. That bit of RAM has always existed; there is no way to know what was stored there before. If it was just requested from the OS, it'll likely be 0 (the OS will erase memory blocks before giving them out for security reasons). If it was previously used by your program, who knows.

    Actually, the results of using an uninitialized variable are undefined. You might get back an unpredictable number, your program may crash, or worse.

    Even if you know that its safe to run the above on your platform, you shouldn't rely on that giving a random value. It will appear random, but is probably actually quite a bit more predictable and controllable than you'd like. Plus, the distribution will be nowhere near uniform.