Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
#include <iostream>
#include <math.h>
using namespace std;
class ip{
private:
string ip;
int result[8];
int sum;
public:
void input(){
/* cout<<"Enter First 8 Binary in Ip address: ";
cin>>ip;
for(int i=0,j=7;i<8 ,j>=0;++i,--j){
if(ip[i]=='1'){
result[i]=pow(2,j);
}else if(ip[i]=='0'){
result[i]=0;
}
}
for(int i=1 ; i<8 ; ++i){
sum=sum+result[i];
} */
cout<<sum<<"\n";
}
};
int main() {
ip convert;
convert.input();
return 0;
}
I was getting some problem while running this code then I understood the problem is with integer initialization...
please help me as I'm getting unwanted output
after running this code my output is: 131
I expected '0' as output
why is it so
You're right, one problem is that you don't initialise sum to zero. Also int i = 1 should surely be int i = 0.
sum=0;
for(int i=0 ; i<8 ; ++i){
sum=sum+result[i];
There are lots of other problems with the code including unnecessary use of a class, unnecessary use of class variables, unnecessary use of floating point functions, unnecessary use of temporary array etc. etc. This program could be much simpler.
In C++, Automatic storage duration integer variables are not initialized to any particular value, and will contain whatever garbage bit pattern that happens to already be in those memory locations. From the perspective of the language standard, the value of the variable is indeterminate, and using it leads to undefined behavior. If you had defined it as a static variable, it would be auto-initialized to 0 in C++.
Most likely your compiler will also throw a warning if you try to use a uninitialized variable.
In GCC, you will see the warning if you compile with below flag:
-Wuninitialized
Warn if an automatic variable is used without first being initialized or if a variable may be clobbered by a setjmp call. In C++, warn if a non-static reference or non-static const member appears in a class without constructors.
Update based on Peter's comment:
In the above case, the code creates an automatic storage duration object of that class type. However, since you just declare an object of type ip as ip convert and you don't have your own constructor which initializes class objects' member values, compiler's default constructor will be called. Most compilers (if not all) will not initialize member values for you and hence you see an output corresponding to the bit pattern present in the memory locations where the object got created.
Related
This question already has answers here:
Uninitialized variable behaviour in C++
(4 answers)
What happens when I print an uninitialized variable in C++? [duplicate]
(4 answers)
Closed 6 months ago.
int main()
{
int a;
cout << a;
return 0;
}
I am wondering why the value 0 is being output. I thought if a variable is uninitialized, it would output a garbage value.
However, I also remember hearing that the default value of an integer is 0 so I am a bit confused.
Thanks
The default behavior of an uninitialized function scope (i.e., local) integer in C++ is for it to be indeterminate, which is fine; however if that value is used before it is defined it introduces undefined behavior, and anything could happen - demons could fly out of your nose.
This page on cppreference provides examples of default integer behavior.
On the other hand, all non-local, thread-local variables, not just integers, are zero initialized. But this case wasn't included in your original example.
(Side note: It is generally considered good practice to simply initialize variables anyway and avoid potential hazards altogether... Especially in the form of global variables. )
There are exceptions to best practice using global variables in rare special cases, such as some embedded systems; which initialize values based off of sensor readings on startup, or during their initial loop iteration... And need to retain a value after the scope of their loop ends.
I think you are not convinced with the answers/comments given, may be you can try the below code:
#include <iostream>
using namespace std;
int main(){
int a,b,c,d,e,f,g,h,i,j;
cout<<a<<endl;
cout<<b<<endl;
cout<<c<<endl;
cout<<d<<endl;
cout<<e<<endl;
cout<<f<<endl;
cout<<g<<endl;
cout<<h<<endl;
cout<<i<<endl;
cout<<j<<endl;
return 0;
}
Well the reason being, a variable gets garbage value( a value unknown/senseless to program) is when someone runs a program, it gets loaded in some part of RAM. Now it all depends what values were previously set to certain location, may be some other program was there previously.
It just happen the your program has loaded into a that location where it happens to be 0 value in RAM and that's what you are getting in return.
It quite possible that if restart your system and try running the same program then you might get garbage value.
Above statements are valid for variables which doesn't get initialized by the compiler.
This question already has answers here:
Uninitialized variable behaviour in C++
(4 answers)
What happens when I print an uninitialized variable in C++? [duplicate]
(4 answers)
Closed 6 months ago.
int main()
{
int a;
cout << a;
return 0;
}
I am wondering why the value 0 is being output. I thought if a variable is uninitialized, it would output a garbage value.
However, I also remember hearing that the default value of an integer is 0 so I am a bit confused.
Thanks
The default behavior of an uninitialized function scope (i.e., local) integer in C++ is for it to be indeterminate, which is fine; however if that value is used before it is defined it introduces undefined behavior, and anything could happen - demons could fly out of your nose.
This page on cppreference provides examples of default integer behavior.
On the other hand, all non-local, thread-local variables, not just integers, are zero initialized. But this case wasn't included in your original example.
(Side note: It is generally considered good practice to simply initialize variables anyway and avoid potential hazards altogether... Especially in the form of global variables. )
There are exceptions to best practice using global variables in rare special cases, such as some embedded systems; which initialize values based off of sensor readings on startup, or during their initial loop iteration... And need to retain a value after the scope of their loop ends.
I think you are not convinced with the answers/comments given, may be you can try the below code:
#include <iostream>
using namespace std;
int main(){
int a,b,c,d,e,f,g,h,i,j;
cout<<a<<endl;
cout<<b<<endl;
cout<<c<<endl;
cout<<d<<endl;
cout<<e<<endl;
cout<<f<<endl;
cout<<g<<endl;
cout<<h<<endl;
cout<<i<<endl;
cout<<j<<endl;
return 0;
}
Well the reason being, a variable gets garbage value( a value unknown/senseless to program) is when someone runs a program, it gets loaded in some part of RAM. Now it all depends what values were previously set to certain location, may be some other program was there previously.
It just happen the your program has loaded into a that location where it happens to be 0 value in RAM and that's what you are getting in return.
It quite possible that if restart your system and try running the same program then you might get garbage value.
Above statements are valid for variables which doesn't get initialized by the compiler.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I was making a simple C++ program using CTable - my custom class. CTable contains a pointer to an array of int, which can be resized and manipulated with CTable methods.
Here's a short snippet:
class CTable
{
private:
int *table; //pointer to the table
int length; //length of the table
///...etc
public:
int SetLength(int length); //returns -1 on failure
int SetValueAt(int index, int value); //returns -1 on failure
///...etc
CTable& operator+=(CTable &other) //combine 2 CTables together
{
int oldLength = length;
SetLength(length+other.GetLength());
for(int i=oldLength;i<length;i++)
{
SetValueAt(i,other.GetValueAt(i-oldLength));
}
return *this;
}
};
I also have another function that I use to split user input into words:
vector<string>* splitString(string sentence, char delim)
{
vector<string> *res = new vector<string>();
stringstream ss;
ss.str(sentence);
string word;
while (getline(ss,word,delim))
{
res->push_back(word);
}
return res;
}
It is important to note that all the methods presented here seem to work fine on their own, i.e. when I test them individually.
As you can see I have also overloaded the += operator. The problem is that whenever I use this operator, the next user input crashes the program when the splitString() function is called. The program crashes with the sole error message "terminate called recursively". No exceptions is thrown, nothing. Only an error code 0xC0000005
I can't really show you the entire code because the program got pretty big, currently about 1000 lines of code. I try to fix this program for hours and I have no idea what's going on. Any help is greatly appreciated !
The windows error code 0xC0000005 means STATUS_ACCESS_VIOLATION. This is typically caused by problem with pointers, out of bound array accesses, memory corruption and other serious issues.
The splitString() function looks ok, so it certainly not causes by itself the kind of behavior you're describing.
The operator+=() looks more suspicious. The code itself seems ok, but it makes assumptions that SetLength() changes the length, reallocates the pointer, and copies all the existing values, all without any problem. Note by the way that this code doesn't handle special case such as doing += on one self.
Unfortunately, the signature of this function is int SetLength(int length);. So the name of the parameter hides the name of the member length, which could cause some serious mismatches that could lead to buffer overflows or unchanged member length (unless you use this->length and length to make the difference between the two).
Finally, you are using raw pointers instead of smart pointers. So you must ensure the rule of 3. If you don't, you will end-up with shallow copies which could also lead to UB (when one of the object releases the memory that it's copy is still using).
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.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
It's a B problem in codeforces
http://www.codeforces.com/problemset/problem/598/B
and i submit this code, but i get Wrong Answer.
It's brute force nothing special, but iam new at problem solving.
#include <iostream>
#include<string>
using namespace std;
int main()
{
char x[10000];
scanf_s("%s",x);
int num;
scanf_s("%d",&num);
int *l = new int[num];
int *r = new int[num];
int *k = new int[num];
for(int i =0;i<num;i++)
{
scanf_s("%d,%d,$d",&l[i],&r[i],&k[i]);
}
char temp;
for(int i =0; i<num;i++)
{
for (int j =0;j<k[i];i++)
{
temp= x[l[i]-1];
x[l[i]-1]=x[r[i]-1];
x[r[i]-1]=temp;
}
}
printf("%s",x);
return 0;
}
Any idea what is wrong or does it need to be optimized ?Is there better way to handle with case of many queries entered ?
scanf is a C function. string is a C++ data type. C++ can often use C datatypes, but it is very rare that C can use C++ datatypes. scanf was written about 20 years before C++ existed and has no clue what a string is.
Next, scanf takes a variable arguments list. It has no clue if the parameter types are correct and cannot easily check. It assumes that the programmer knows what they are doing.
End result, it tries to place char data as specified by the %s format option into a string. The string is written over with incompatible data and undefined behaviour occurs.
Replace the scanf with
cin >> x;
and go all C++. Alternative is to eschew C++ and go C style:
char x[appropriate size goes here];
scanf("%s",x);
Don't know the appropriate size? That's going to be a problem. string resizes to fit. The char array expected by scanf cannot. If you read more data than you can fit, Undefined Behaviour.
In
scanf("%d",num);
%d says the programmer passed in a pointer to an integer, in this case it would be the location of num so that scanf can update the value stored at num with whatever was read. The value of num was passed in. scanf assumes this is a pointer and Undefined Behaviour results. Most likely whatever uninitialized garbage value that is in num is used as a memory location and some unsuspecting block of memory gets overwritten. This will cause problems at some point in the future when you actually need the data that was at that memory.
scanf("%d",&num);
or in C++
cin >> num;
The remaining problems are variations on the preceding two problems.
scanf("%d,%d,%d",l[i],r[i],k[i]);
needs pointers
scanf("%d,%d,%d",&l[i],&r[i],&k[i]);
and
printf("%s",x);
wants a char array, not a string.
printf("%s",x.c_str());
gets the char array equivalent to the string.
Recommendation: Compile with a higher level of intolerance to errors that the compiler can survive. In g++ I use at least -pedantic -pedantic-errors -Wall -Wextra -Werror.
On a logical front, your input is all unchecked. A user could type in "rutabaga" for num with possibly comical results as your program tries to deal with non-numeric input. Again Undefined Behaviour. The program could crash. It could lock up. It could impregnate a male Llama.
In C++
if (cin >> num)
will catch some but not all forms of bad input. If this test fails, the contents of num are undefined and should not be used. Further, the stream will be in an error state and unreadable until the error is acknowledged and cleared. In C the equivalent is
if (scanf("%d",&num) == 1)
if scanf read exactly one value, num, all is good. Any other number of values read means scanf did not succeed and the contents of num are undefined.