Need explanation on short code snippet [duplicate] - c

This question already has answers here:
What happens to a declared, uninitialized variable in C? Does it have a value?
(9 answers)
Closed 5 years ago.
I just made this short program. Can someone please explain why I am getting 2 as a result here?
Here is the code
#include <stdio.h>
#include <stdlib.h>
int main()
{
int variable;
int a;
a=variable;
a=200;
printf("%d",variable);
return 0;
}

Because you print the value of an uninitialized variable. It will have an indeterminate (and seemingly random) value.
The assignment you make to a just copies the value of variable and then of 200 into a. The value of variable remains unmodified and indeterminate.
I recommend you find a good beginners book or two to read.

At the beginning, you define two variables, a and variable. Note, that those variables at this point are not initialized. Right now, the compiler only knows that there are two variables of type int and their names, nothing more.
You then try to initialize variable a with the not initialized variable variable, the result should be clear: The two variables remain uninitialized.
Then you proceed and initialize a with 200, variable is still only defined, not initialized.
After that, you print the still uninitialized variable variable, which hasn't recieved any "real" value as of yet, only what already was "lying around" in memory when the compiler assigned that memory location to the variable. In your case, that was "2" (or at least, that's what printf could extract from there).
Further reading: C Variables. This explains how variables are defined, declared and initialized.

Assigment operator (a = variable;) does not link the two variables, just assignes whatever value there is in the righthandside expression to the left handside.
You can visualize local variables as boxes where you can put values into.

In c if you don't assign a value to the variable then it stores the garbage value which can be anything.In your code you did not assign the value to variable so it print 2 (which can be anything)

Related

C variable initialization and execution [duplicate]

This question already has answers here:
Is un-initialized integer always default to 0 in c?
(4 answers)
Closed 1 year ago.
In C, we know that without initializing a variable, it holds a garbage value. Yet in online compilers and also, in an IDE, when I tried this program it got compiled and there was a perfect output. When I tried to print the same without the while loop, it returned a garbage value. So, is not initializing fine?
#include <stdio.h>
int main() {
int j;
while(j<=10){
printf("\n %d",j);
j=j+1;
}
}
Try disassembling your code, for example "gcc -S test.c", so you can see that there is no instruction dedicated to initializing the integer "j" with or without loop. Greetings.
… it holds a garbage value.
When anybody says an object has a garbage value, they are being imprecise with language.
There is no value that is a garbage value. For 32-bit two’s complement integers, there are the values −2,147,483,648 to +2,147,483,647. Each of them is a valid value. None of them is a garbage value.
What it actually means to say something has a garbage value, if the speaker understands C semantics, is that the value of the object is uncontrolled. It has not been set to any specific value, and therefore whatever value you get from using it is a happenstance of circumstances. It may be some value that was in the memory of the object before it was reserved to be the memory for that object.
However, it might be other things. When an object is uninitialized, the C standard not only has no requirement that the memory of the object have any particular value, it has no requirement that the object behave as if it had any fixed value at all. This frees the compiler for purposes that are useful for optimization in other situations. But it means that, if you have int x; printf("%d\n", x); int y = x+3; printf("%d\n", y);, the compiler does not have to load x from memory each time it is used. Because x is uninitialized, the compiler is not required to do any work to load it from memory. For the printf("%d\n", x);, the compiler might let x be whatever value is in the register that would be used to pass the second argument to printf. For the int y = x+3;, the compiler might let x be whatever is in some other register that it would use to hold the value of x if x were defined. This could be a different register. So printf("%d\n", x); might print “47” while int y = x+3; printf("%d\n", y); prints “−372”, not “50”.
Sometimes an uninitialized object might behave as if it started with the value zero. This is not uncommon in short programs such as the one in the question, where nothing has used the stack much yet, so the part of it reserved for j is still in the initial state the program loader put it in, filled with zeros. But that is happenstance. When you change the program, the compiler might use a different part of the stack for j, and that part might not have zeros in it, because it was used by some of the initial program start-up code that runs before main starts.
Always avoid use a uninitialized variables, because it cause undefined behavior.
Uninitialized variables
Unlike some programming languages, C/C++ does not initialize most variables to a given value (such as zero) automatically. Thus when a variable is assigned a memory location by the compiler, the default value of that variable is whatever (garbage) value happens to already be in that memory location! A variable that has not been given a known value (usually through initialization or assignment) is called an uninitialized variable.
For your reference:
https://wiki.sei.cmu.edu/confluence/display/c/EXP33-C.+Do+not+read+uninitialized+memory
https://www.learncpp.com/cpp-tutorial/uninitialized-variables-and-undefined-behavior/

What will output to print a unrecognized int variable? [duplicate]

This question already has answers here:
(Why) is using an uninitialized variable undefined behavior?
(7 answers)
Closed 3 years ago.
if i run this program:
#include <stdio.h>
int main()
{
int a=32,b=2,c,i;
for(i=0;i<3;i++){
printf("%d\n",c);
c=a/b;
a=c;
}
return 0;
}
the output is:
32765
16
8
In there, I dont define the value of C, Where from came this output 32765.?
even again i run this code more time,it show different values like 32764,32767. Why this different output showing on?
Because c has automatic storage duration (i.e. is a non-static local variable) and is uninitialized, its value is indeterminate. Attempting to print an uninitialized variable that never had its address taken (i.e. was not the subject of the address-of operator &) invokes undefined behavior.
Even if you did take the address of c you could still have undefined behavior if it contains a trap representation. If it does not contain a trap representation (and most implementations don't have them), the the value is unspecified which simply means the printed value can't be predicted.
Automatic variables (a local variables which are allocated and deallocated automatically when program flow enters and leaves the variables's scope) for which there is no explicit initializer have undefined (i.e. garbage) values.

Is there any fixed assignment for int and char if not assigned? [duplicate]

This question already has answers here:
What happens to a declared, uninitialized variable in C? Does it have a value?
(9 answers)
Closed 5 years ago.
#include<stdio.h>
void main(void)
{ char m,n;
printf("%d\n",m);//value of m
printf("%d",n);//value of n
}
in the above snippet value of m is always printed as 0 why?why it doesn't change even after multiple times compilation is it automatically assigned if we do not assign while the value of n always changes so why not both change randomly every time i compile?
Am i missing any concept?
Local variables like yours are automatic variables. They are allocated on stack memory and their value is garbage.
Global variables are implicitly have static storage class and have value 0 by default.
Since m is a local variable, its value needn't always be the same. It is indeterminate. This memory location can be given to other processes.

What happens in C when you print a declared, but unassigned variable?

Why does the following snippet cause random numbers to print to the screen with printf, but putchar always outputs 1?
#include <stdio.h>
int main() {
char c;
printf("%d\n", c );
putchar(c);
}
According to C99 standard, this is undefined behavior. Let's see why:
Section 6.7.8.9 says that
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.
This applies to your variable c, because it has automatic storage duration, and it is not initialized explicitly.
Section J.2 says that
The behavior is undefined in the following circumstances:
...
The value of an object with automatic storage duration is used while it is
indeterminate
This applies to your code as well, because you read c when you pass it as a parameter to both printf and putchar, and the value of c is still indeterminate, because it has not been assigned.
1) The c variable first has a random value(default/garbage value) to itself as you declared-but-did-not-initialize your char c to any defined letter or value of ur interest(character).
2) Next you tried to printf the %d(digit/decimal/numerical value) of the char c, so now it is giving you a converted value of the garbage which was earlier assigned to c when you declared the char c in the first place.
3) Finally you tried to use putchar(c), which again behaves similarly because your char c is uninitialized and is still being read thereby re-trying to manage with an undetermined value to be printed onto the screen. (since the same un-initialized character variable c is being passed to both kind of printing as a parameter).
Yes these 3 statements are a bit clumsy to understand but they are as layman as it can get to help speed-up some understanding regarding this query of yours.
Pay attention to the 1st comment response to your question by #bluemoon. Those 3 words alone litterally have a huge amount of sensibility and meaningfull-ness to them, to a point that it also tells you what you have done erroneous in your own code(your actions)."UNDEFINED"(try relating the same with UNINITIALIZED).

strange behavior in c [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can a local variable's memory be accessed outside its scope?
I recently came across the following code:
#include <stdio.h>
int* abc () {
int a[3] = {1,10,100};
return a;
}
int* xyz () {
int b[1] = {222};
return b;
}
int main() {
int *a, *b;
a = abc();
b = xyz();
printf("%d\n", *a);
return 0;
}
the output is 222. 'a' is pointing to the array declared inside the xyz().
my question is:
why is a pointing to the array declared inside xyz().
the array declared inside the function xyz() should go out of scope after the execution of the function. why is that not happening ?
2: It is happening, and the entire program has undefined behaviour. It is not a correct program, and there's little point musing about ifs and buts.
You might see 222 because the memory that was used for the local array in abc has been used for something else - the stack for the function xyz. And you're passing around an address to that memory. Make a few more function calls and *a may contain some other value.
should go out of scope after the execution of the function. why is that not happening ?
The variable has gone out of scope. Using that address outside the function is incorrect code: using a pointer to local data returned from a function is undefined behavior.
The variables a and b are automatic variables; using their adress in a other function is an undefined behavior. Anything can happen : you can't expect an output (eg, an optimizing compiler can delete some illegal code).
to return a pointer it must be a pointer to dynamically allocated variable or static or global variable.
returning a pointer to a stack variable will cause you to have pointer to the stack which will be reused when you call a new method.
it happened in your case to reuse the stack variable for another array and overwrite the old value stored when you called the first method.
try to call printf again you will see different output because the first call to printf changed the stack content.
why is that not happening ?
It does happen, just formally. Undefined behavior is not obligated to crash or to misbehave - they "anything might happen" means it can also run seemingly without any error. I just answered a similar question.
The functions abc and xyz are each passing back an address to a locally created array. Subsequent calls are mashing the memory that was previously used (and passed back to you).
These are called automatic local variables.
You'll need to declare those arrays as static or allocate the memory in a different way.

Resources