How a garbage value is assigned in c/c++ [duplicate] - c++

This question already has answers here:
How garbage values are assigned to variables in c
(6 answers)
Closed 9 years ago.
In C++/C if we don't initialize a variable, it will have some garbage values right? I would like to know from where these values are coming? Is it assigned by the compiler? Does this value have range? Is it the previous value present in the memory allocated to that variable? If yes can 5 or 500 be a garbage value?
This is not for any coding purpose, I just what to know it for learning.

Any value can be garbage. It's whatever was left over in that spot of memory from the last operation that occurred there. It is unpredictable and never reliable, but it could be 5 or 500.

Assuming the compiler doesn't do anything special (which it might if you're doing a debug build), it'll be whatever happens to be in memory at the time.
It cannot be depended upon.

It could be whatever value was in the memory position previously. It could be a magic value such as 0xCD, placed there by the debugger. It could be set to 0 for you by the compiler. It could be a value which isn't legal for the type (for example, not equal to any enum values).

You get the value that is already there. So yes, this could very well be "5".
Note: if you run in DEBUG mode the environment will usually get zeroed memory, this is one way to get the weird behaviour we call "Heisenbugs" :-)

The garbage value is not assigned, rather the value is already there. When you allocate a variable you are reserving a piece of memory - until you overwrite it that memory will contain whatever "random" information was there before. Check this link which has the answer
Link

Related

What determines the "random" location pointed to by uninitialized pointers? [duplicate]

This question already has answers here:
Why is the phrase: "undefined behavior means the compiler can do anything it wants" true?
(2 answers)
Uninitialized variable behaviour in C++
(4 answers)
What happens to uninitialized variables? C++ [duplicate]
(3 answers)
Where exactly does C++ standard say dereferencing an uninitialized pointer is undefined behavior?
(7 answers)
What are the debug memory fill patterns in Visual Studio C++ and Windows?
(3 answers)
Closed 5 months ago.
For uninitialized pointers, such as
int * temp;
what determines the random location in memory that they end up pointing to? Does c++ use a random number generator to fill a memory address for my uninitialized pointer?
An uninitialized variable usually contains whatever pre-existing data was already present in the memory that the variable occupies.
Although, some compilers do fill in uninitialized memory with preset byte patterns in debug builds to aid in debugging. See Debug values for some examples, and also see What are the debug memory fill patterns in Visual Studio C++ and Windows?
Nothing, it's undefined. It is not "random", it is simply non-deterministic. in practice, the value of any initialised variable is determined by whatever happens to be in the memory that the variable occupies. That may for example be leftover from previous operations, as initialised by the system on start-up, or just however the physical hardware behaves. None of that is deterministic but unlikely to be in any sense random.
The point is that undefined behaviour is usually the result of the compiler doing exactly nothing and accepting the result will be undefined. So no, the compiler does not generate a random number - that would be initialisation. Pointless initialisation, but initialisation nontheless.

Can my program use unallocated memory on the free store without my knowledge?

When defining a variable without initialization on either the stack or the free store it usually has a garbage value, as assigning it to some default value e.g. 0 would just be a waste of time.
Examples:
int foo;//uninitialized foo may contain any value
int* fooptr=new int;//uninitialized *fooptr may contain any value
This however doens't answer the question of where the garbage values come from.
The usual explanation to that is that new or malloc or whatever you use to get dynamically allocated memory don't initialize the memory to some value as I've stated above and the garbage values are just leftover from whatever program used the same memory prior.
So I put this explanation to the test:
#include <iostream>
int main()
{
int* ptr= new int[10]{0};//allocate memory and initialize everything to 0
for (int i=0;i<10;++i)
{
std::cout<<*(ptr+i)<<" "<<ptr+i<<std::endl;
}
delete[]ptr;
ptr= new int[10];//allocate memory without initialization
for (int i=0;i<10;++i)
{
std::cout<<*(ptr+i)<<" "<<ptr+i<<std::endl;
}
delete[]ptr;
}
Output:
0 0x1291a60
0 0x1291a64
0 0x1291a68
0 0x1291a6c
0 0x1291a70
0 0x1291a74
0 0x1291a78
0 0x1291a7c
0 0x1291a80
0 0x1291a84
19471096 0x1291a60
19464384 0x1291a64
0 0x1291a68
0 0x1291a6c
0 0x1291a70
0 0x1291a74
0 0x1291a78
0 0x1291a7c
0 0x1291a80
0 0x1291a84
In this code sample I allocated memory for 10 ints twice. The first time I do so I initialize every value to 0. I use delete[] on the pointer and proceed to immediately allocate the memory for 10 ints again but this time without initialization.
Yes I know that the results of using an uninitialized variable are undefined, but I want to focus on the garbage values fro now.
The output shows that the first two ints now contain garbage values in the same memory location.
If we take the explanation for garbage values into consideration this leaves me only one conclusion: Between deleting the pointer and allocating the memory again something must have tampered with the values in those memory locations.
But isn't the free store reserved for new and delete?
What could have tampered those values?
Edit:
I removed the std::cout as a comment pointed it out.
I use the compiler Eclipse 2022-06 comes with (MinGW GCC) using default flags on Windows 10.
One of the things you need to understand about heap allocations is that there is always a small control block also allocated when you do a new. The values in the control block tend to inform the compiler how much space is being freed when delete is called.
When a block is deleted, the first part of the buffer is often overwritten by a control block. If you look at the two values you see from your program as hex values, you will note they appear to be addresses in the same general memory space. The first looks to be a pointer to the next allocated location, while the second appears to be a pointer to the start of the heap block.
Edit: One of the main reasons to add this kind of control block in a recently deallocated buffer is that is supports memory coalescence. That two int signature will effectively show how much memory can be claimed if that space is reused, and it signals that it is empty by pointing to the start of the frame.
When defining a variable without initialization on either the stack or the free store it usually has a garbage value, as assigning it to some default value e.g. 0 would just be a waste of time.
No. The initial value of a variable that is not initialized is always garbage. All garbage. This is inherent in "not initialized". The language semantics do not specify what the value of the variable is, and reading that value produces undefined behavior. If you do read it and it seems to make sense to you -- it is all zeroes, for example, or it looks like the value that some now-dead variable might have held -- that is meaningless.
This however doens't answer the question of where the garbage values come from.
At the level of the language semantics, that question is non-sensical. "Garbage values" aren't a thing of themselves. The term is descriptive of values on which you cannot safely rely, precisely because the language does not describe where they come from or how they are determined.
The usual explanation to that is that new or malloc or whatever you use to get dynamically allocated memory don't initialize the memory [so the] values are just leftover from whatever program used the same memory prior.
That's an explanation derived from typical C and C++ implementation details. Read again: implementation details. These are what you are asking about, and unless your objective is to learn about writing C and / or C++ compilers or implementations of their standard libraries, it is not a particularly useful area to probe. The specifics vary across implementations and sometimes between versions of the same implementation, and if your programs do anything that exposes them to these details then those programs are wrong.
I know that the results of using an uninitialized variable are undefined, but I want to focus on the garbage values fro now.
No, apparently you do not know that the results of using the value of an uninitialized variable are undefined. If you did, you would not present the results of your program as if they were somehow meaningful.
You also seem not understand the term "garbage value", for in addition to thinking that the results of your program are meaningful, you appear to think that some of the values it outputs are not garbage.

Where do values from unintialized variables come from? [duplicate]

This question already has answers here:
How does an uninitiliazed variable get a garbage value?
(5 answers)
Closed 8 years ago.
When you declare a local variable i like so :
int i;
And you use this variable, you will get undefined behaviour because i isn't initialized yet. But i holds a value, a "garbage" value, where does this value come from? is it from a random place in memory?
You don't know, you can't tell. Undefined behavior means that anything can happen.
That said, in practice on most implementations and most of the time int i; will reserve sizeof(int) bytes on the stack (which is usually somewhere in main memory), so the value of i will be whatever happens to be on the stack at this moment.
But don't rely on it, and remember that this isn't always true.
Its whatever was in memory at &i before.

unassigned value in the int[ ]

Would like to know in C++ what the value of unassigned integer in an int[] usually is.
Example
int arr[5];
arr[1]=2;
arr[3]=4;
for(int i=0;i<5;i++)
{
cout <<arr[i] <<endl;
}
it print
-858993460
2
-858993460
4
-858993460
we know that the array will be {?,2,?,4,?} ,where ? is unknown.
What will the "?" be usually?
When I tested , I always got negative value.
Can I assume in C++ unassigned element in the integer array is always less than or equal to zero?
Correct me if I'm wrong. When I study in Java unassigned element in array will produce null.
Formally, in most cases the very attempt to read an uninitialized value results in undefined behavior. So, formally the question about the actual value is rather moot: you are not allowed to even look at that value directly.
Practically, uninitialized values in C and C++ are unpredictable. On top of that they are not supposed to be stable, meaning that reading the same uninitialized value several times is not guaranteed to read the same value.
If you need a pre-initialized local array, declare it with an explicit initializer
int arr[5] = {};
The above is guaranteed to fill the array with integer zeros.
When I tested , I always got negative value.
The (previously) unused memory space seemed filled with the hex code 0xCC. However, as mentioned above -- several times -- you cannot rely on this.
In one of your comments you clarify your task:
im trying to create an int array let say of the size 100 and randomly insert postive integer into any position in the array. If the array is not full. how could i determine if that position in the array has never been assigned[?]
Fill the array with zeros (manually, or per AndrewT's answer). Since you are inserting positive integers only, all you have to test for is !0.
You can't know what this will produce, since it takes as value the bits that are in memory in that moment. So you can get ANY value, not only negative values.
The values contained in an unitialized area of memory can be anything, it is implementation depending. The most efficient implementation is to leave the memory as it was, so you will find in your array whatever was contained before. An important note: it is not something you can use as a random value. Some implementation (I have seen that, especially in the past, when compiling and running in debug mode) might put zeros in your memory, but it is uncommon. You simply should not rely on the content of uninitialized area of memory.
To understand if something has not been touched in your array, you can initialize it to some value like DEADBEEF:
http://en.wikipedia.org/wiki/Hexspeak
(Unless you are so unlucky that one of the values you have to insert corresponds exactly to DEADBEEF... :) )
These are garbage values, you cannot expect to work with these variables properly and they will not predict what it may result into. Whenever a variable gets allocated some portion of memory gets allocated for that variable and those portion may be used previously for some other unknown calculation which you cannot know, so you have to intialize those variables with some values to avoid usage of garbage values.
You are not assigning any value at these locations. So it will return garbage values from memory. You must put some values at these locations. Unimplemented locations will returned in some unexpected/unpredictable values.

garbage values in C/C++ [duplicate]

This question already has answers here:
Closed 12 years ago.
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?
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.
If by "garbage values" you mean the values of uninitialized variables, it doesn't -- the value of an uninitialized variable is undefined by the standard. The garbage value you're thinking of is actually just whatever happened to be stored in that memory right before the storage for the variable was allocated from the stack or heap.
That said, some compilers offer debugging aids that will fill uninitialized variables with some well-known "magic number" to help you catch errors of this sort. For example, Microsoft Visual C++ fills uninitialized stack variables with 0xCCCCCCCC. These are specific to the compiler and usually require that you compile with debugging turned on.
The memory your program happens to use comes up in some state, controlled by how the electrons flowed at power up, funny properties of the silicion, what was in the memory before, and sometimes cosmic rays.
It isn't random, but it is extremely hard to predict.