This question already has answers here:
What happens when I print an uninitialized variable in C++? [duplicate]
(4 answers)
Closed 1 year ago.
#include <iostream>
using namespace std;
int main()
{
int a;
int b;
cout<<a<<endl;
cout<<b;
}
Why b has 16 value when i compile this? I cant understand why b has 16 not 0. Int doesnt have 0 as default value?
Absolutely not. C++ does not initialise variables unless you ask it to. (Setting a variable to 0 for example is at least one instruction: typically reg XOR reg. That could be wasteful.) The behaviour of reading an uninitialised int is undefined.
(Note you can do some things with uninitialised variables, such as setting a pointer or reference to one, computing sizeof(a), and using decltype(a). But passing it by value to a function is undefined behaviour. That often trips up even professional programmers.)
Related
This question already has answers here:
Are variable length arrays there in c++?
(2 answers)
Array[n] vs Array[10] - Initializing array with variable vs numeric literal
(1 answer)
Closed 1 year ago.
Given that user input is taken at runtime but array is created during compile time. How and why does this piece of code work?
#include <iostream>
using namespace std;
int main(){
int n;
cin>>n;
int arr[n]; //Why can I use this statement to create an array?
}
It's a non-standard extension, supported by gcc and clang.
It works by allocating space on the stack at the point the array is declared, a bit like alloca.
The memory allocated is automatically freed (by adjusting the stack pointer) when the function returns (or arr goes out of scope).
This question already has an answer here:
Why are consecutive int data type variables located at 12 bytes offset in visual studio?
(1 answer)
Closed 4 years ago.
Assuming I have two variables in my scope.
int a, b;
Is it safe to assume that they will be stored one after the other in the process' memory? (with a difference of sizeof(int))
If that scope is local function scope then no, it's not safe to assume. The standard gives you no guarantees on this. (as opposed to structs)
No , it is not safe to assume.
But most of times , they will be stored one after the other in the process' memory.
Like this :
#include<iostream>
using namespace std;
int main()
{
int a,b;
cout<<&a<<endl;
cout<<&b<<endl;
int c;
int d;
cout<<&c<<endl;
cout<<&d;
}
Output for the following program is :
Here , we can easily notice that these four addresses are simply four contiguous memory blocks( with a difference of sizeof(int)).
This question already has answers here:
How to access a local variable from a different function using pointers?
(10 answers)
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 6 years ago.
This is my C++ code .
According to me , it should give output:
abc
Garbage
abc
But it is giving output:
abc
Garbage
Garbage
#include<bits/stdc++.h>
using namespace std;
char **func()
{
char* PA = new char[10];
PA[0]='a';
PA[1]='b';
PA[2]='c';
PA[3]='\0';
printf("%s\n",PA);
printf("Garbage\n");
char **PPA = &PA;
return PPA;
}
int main()
{
printf("%s\n",*func());
return 0;
}
Where am I doing wrong?
char **PPA = &PA;
Retrieves the address of the variable PA itsself, which is an automatic variable and goes out of scope as soon as the function terminates. That means you have undefined behavior here. The C standard doesn't guarantee any consistent behavior, so anything may happen, including what you experienced.
To fix that, you could change the function prototype to char* func() and return PA directly and remove PPA altogether.
This question already has answers here:
What happens when I print an uninitialized variable in C++? [duplicate]
(4 answers)
Closed 6 years ago.
i am currently learning C++ and i had a question about some "weird" things i noticed while testing what i have learnt.
So i use this :
int marc[9];
int sum = 0;
for (int x =0; x < 9; x++) {
marc[x] = x*4;
sum += marc[x];
}
cout << sum << endl;
And i get a normal result which is 144
However, if i changed
int sum = 0;
to
int sum;
I got a crazy result like 19557555002
So i was wondering what is happening in the second case?
Thanks for your answer :)
You are operating on uninitialized memory in the second case. Non-static local variables are not initialized to zero by the runtime like in other languages, if you need sum to have a defined value, you must initialize it yourself. The 19557555002 will be the integer interpretation of any bytes that were present at the memory address allocated for sum.
Further reading: What happens to a declared, uninitialized variable in C? Does it have a value?
Its called an undefined behavior and it happens when you don't initialize your variables.
int sum;
above code can only declare a variable but it doesn't initialize it by default so the variable contains a garbage value.
this creates an uninitialized int int sum;
it can have "garbage" values, and this is exactly what happened to you
how this happens: let's say you use an int x in address y, and sets it to 19557555002. now, lets say you "leave" that address (go out of scope, program terminates, OS takes that memory...) and someone else takes it because he wants to put there a new int. if he just declares his int, without initializing it, his int can be stationed (if the OS so desires...) in address y, that previously used to hold your int, which means in address y, he will find 19557555002. That is what could happen to you if you don't initialize variables.
Memory for local variables is typically allocated on the stack. This means that without some initialization, they will hold some data that was residing there previously.
As others said it is undefined behavior, but practically, on most implementations, it results in effects like this:
void foo()
{
int a = 5;
}
void bar()
{
int b;
std::cout << b;
}
void someCaller()
{
foo();
bar();
}
On most implementations, this will usually result in the printing of 5 on the stdout.
Note that some compilers like MSVC initialize all variables in Debug configuration, but usually any kind of optimization flags will avoid initializing memory, if not explicitly requested.
This question already has answers here:
How is a variable at the same address producing 2 different values? [duplicate]
(4 answers)
Closed 7 years ago.
#include <iostream>
using namespace std;
int main()
{
const int kiNum = 100;
int* ptr = const_cast<int*>(&kiNum);
*ptr = 200;
cout<<"kiNum: "<<kiNum; // The value still prints 100 on the console??
return 0;
}
output:
kiNum = 100
In the above code snippet , i am trying to change the value of a const integer, after const_cast and then change the value at the address, but the console still prints the old value (i am using visual studio 2012)
Writing to something which is defined as const is undefined (assuming you cast away the const of course).
http://en.cppreference.com/w/cpp/language/const_cast
It's a pretty accurate website. If you have issues with a language feature its always worth looking up there IMHO.