Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Debug why the below mentioned code goes into an infinite loop
int a[10];
int i;
for(i=0;i<=10;i++) {
a[i]=0;
}
i am not able to find any valid explanation for it.
Although one possibility is a[9] pointing back to i ... but it doesn't seem convincing
Classic side effect of "Buffer overflow". In this case what is happening is that the value of i is getting overwritten. Check the range of variable a it's an array of 10 bytes 0 through 9. However you loop for 11 bytes 0 through 10.
Change the loop as
int a[10];
int i;
for(i=0;i<10;i++) {
a[i]=0;
}
and it won't go in infinite loop. Again this is a problem of "buffer overflow" and can have undefined behavior. In your case that undefined behavior is infinite loop.
For the value of i equals to 10,
a[i]=0;
is off by one access. It invokes undefined behavior. Anything can happen.
This code has undefined behavior. But if it is going into infinite loop the most suitable explanation would be that a[10] = 0 is overwriting i with 0, since i is defined immediately after a, therefore, in memory is most probably placed as a contiguous element after array elements.
You could try this so that you don't get undefined behavior:
int i, a[10];
for(i = 0; i <= 9; i++)
a[i]=0;
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm trying to write a program for a factorial which tries to calculate as such.
If n is the natural number, then the answer is n*(n-1)(n-2)....1(-1)(-2))(-3)...*(-10)
Here is C++ code which just doesn't go beyond printing n. It works without the if else statement.
#include <iostream>
using namespace std;
int main() {
int val=0, prod=1;
std::cout<<"Enter the number"<<std::endl;
std::cin>>val;
std::cout<<"The number is "<<val<<std::endl;
while(val>=-10)
{
prod=prod*val;
if (val=1)
{
val=val-2;
}
else
{
val=val-1;
}
}
std::cout<<prod<<std::endl;
return 0;
}
if (val=1)
should be
if (val==1)
= for assignment and == for comparison.
I would expect your compiler to warn you about this very common error. If it didn't you should find out why, if it did you should pay attention.
Compiler warnings will save you loads of time in the long run.
Sometimes programming tests are about common sense, like in this one:
You say that you need to calculate:
n*(n-1)*...*1*(-1)*(-2)*...*(-10)
This is the same as (there's an even number of negatives, so it becomes positive):
n*(n-1)*...*1*fact(10) // fact(10)=3,628,800
So, I would just write the function for calculating the factorial of a number and multiply the result by 3,628,800.
Obviously, there might a catch: fact(10) is about three million, while on most computers, the maximum value of int (the basic type you're using) is about two billion, which is not even a thousand times larger than the value you need to multiply with.
So, instead of using a simple int, I'd suggest you to use integer types which can hold larger numbers, like long long or unsigned long long. Maybe this is the real purpose of this exercise?
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 months ago.
Improve this question
Giving this code:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int k, x;
while(k > x-3) {
k--;
// cout << "x = " << x << "\n";
}
x++, k--;
int aux = abs(k-x);
cout << aux;
}
When we run it, it always pops up a constant x (x = 50) and the absolute value between the integer k and the x is always 5. Can you please explain me why and how does this works?
With the constraint of "k is greater than x", this piece of code here
while(k > x-3) {
k--;
// cout << "x = " << x << "\n";
}
Will decrease k to be 3 less than x.
The next line, x++, k++; increases them both by 1, but it doesn't change the result. k is still 3 smaller than x.
k-x is -3 and abs(k-x) is 3, hence why the program always prints 3. Assuming, of course, that both k and x are initialized and that k is bigger than x. The program as it is posted with k and x uninitialized exhibits undefined behavior, so there's no guarantee on what is going to happen. Also, as Aconcagua points out, if x is smaller than INT_MIN + 3, that also leads to undefined behavior.
I really think you should try two arbitrary numbers.
For example , imagine we are using k= 10 & x=8.
Your loop will look like:
While(10>5) 10-1=9 ... and so on, until K is not greater than (X-3).
You will get k=5, and x is the same value,8.
After the while loop you decrement k, and increment x, so k=4 and x=9.
Abs(k-x) = 5.
If you want the more theoretical explanation, the loop will grant that the difference between your two variables is 3, the X will be greater than K.
As after the loop you decrement K and increment X , the diference between them will ALWAYS be 5.
Matthieu and πάντα ῥεῖ are correct: Ths is classic undefined behavior. (One rationale for making it undefined and not simply unspecified or implementation defined is that some architectures have flags for uninitialized registers and would trap.) A compiler is actually free to compile it to an empty program: Reading an uninitialized variable can result in anything — and nothing is a subset of anything. All subsequent code after the undefined behavior is "tainted" by the preceding error and can be omitted. Note that different architectures and different compilers, possibly even different C standard libs (with the same compiler!) may give different results; even a different compiler flag (concerning optimization or function call conventions) may change this undefined behavior.
(The rest of this answer applies to the version of the question where the line after the loop read x++, k++; (instead of k-- as it is now).)
But you have encountered a consistent behavior, and the question is why it is consistent. The first assumption is that the compiler does not simply generate code to output "5", (which it could, legitimately) but actually "naively" generates machine code that corresponds to the C statements. We'll reason along the statements.
Then the behavior indicates that the memory locations where x and k reside are containing values which make k > x -3 false right away. (Otherwise, k would be decremented until the difference is 3, not 5).
If the condition is false, the variable difference will not change; from that we can conclude that it was 5 from the start with x-k == 5. If you omit the abs(), the output should be -5.
The reason the variables have these consistent intial values may be connected to things the operating system or C runtime environment do at program startup, like initializing the standard streams. Try using printf instead of cout and see if the result changes.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
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.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I am trying to use string::length() inside a function I wrote, named match(), but I'm getting garbage values.
Why does the marked line is outputting garbage values?
#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;
void match(string st1,string st2)
{
for(int i=0;i<st1.length();i++)
{
cout<<"Why this value is garbage "<<(i-st1.length()-1)<<"\t";
// this expression gives wrong values ^^^^^^^^^^^^^^^
}
}
int main()
{
string st1,st2;
cout<<"Enter the required string\n";
cin>>st1>>st2;
match(st1,st2);
return 0;
}
imagine a string "foo":
i-st1.length()-1 means:
when i is 0:
0 - 3 = -3
- 1 = -4
but st1.length() is a size_t, which is unsigned, so all terms in the expression are promoted to unsigned values.
(unsigned)0 - (unsigned)3 = 0xfffffffffffffffd
- 1 = 0xfffffffffffffffc
= 18446744073709551612
The problem is that i is an int value, while string::length will return you a size_t value. The first one is a signed value, while the second is unsigned. One way to prevent this is to cast your st1.length() as an int, so all the elements in your operation are signed values. You will then get the value you are looking for.
i-(int)st1.length()-1
This is not garbage, you are implicitly converting/promoting a signed type (i is signed int) to an 'unsigned' one (the return type of length() is size_t which is unsigned).
It happens implicitly because an unsigned type is more powerful than a signed one. This is a common source of bugs in the C/C++ world.
This is what you need to modify:
cout<<" **NOT** garbage "<<(i-(int)st1.length()-1)<<"\t"<<endl;
Happy programming!
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 8 years ago.
Improve this question
Here is the simple code of for loop. Theoretically after for loop, the value of i should increase to 1 but the value is not increasing; i retains the value 0 after the loop also. Can you provide me the reason behind this?
Integer j = 0;
Integer i = 0;
for(; i < m_ParticleNum; ++i)
{
if(m_aOutputParticleID[i] < 0 )
{
m_aOutputParticleID[i] = i;
m_aOutputParticlePosition[i] = bucket[j].Position;
m_aOutputParticleVelocity[i] = bucket[j].Velocity;
m_aOutputParticlePressure[i] = bucket[j].Pressure;
m_aOutputParticleDensity[i] = bucket[j].Density;
m_aOutputParticleTemperature[i] = bucket[j].Temperature;
m_aOutputParticleKineticViscosity[i] = bucket[j].KineticViscosity;
m_aOutputParticleSolidPhaseRate[i] = bucket[j].SolidPhaseRate;
m_aOutputParticleType[i] = bucket[j].Type;
j++;
}
}
If the value of m_ParticleNum is 0, the loop does not execute and so, the value of i stays 0.
Is the value i used in any calculation or output after the loop?
If you are just inspecting i using the debugger, it may be optimised so it doesn't retain a value. There is no guarantee that the compiler has to retain values in unused variables.
Also, if there is any range checking going on which causes the loop to be exited with an exception, the increment of i at the bottom of the loop will be bypassed.
Finally, as i is a user-supplied class Integer, it is possible that some nasty person has defined its operators so the ++ operator is broken/disabled by design and is not incrementing the value.
We really need to see how you are evaluating i after the loop and the declaration of the type Integer to be able to provide a better diagnosis.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I recently started learning C++ and I'm a bit confused with pointers. Could you please explain me WHY in the following example variable "a" equals 1 and z = 0?????? I'm really confused!!!!!!
#include<iostream>
using namespace std;
void main()
{
int a;
int Z[3] ={1, 2, 3};
int *z;
z=Z;
a = (*z)--;
cout<<a<<" "<<*z<<"\n";
system ("pause");
}
logically ,I believe, first of all *z points to the 0-th element of the array - that is 1
then -- operator decreases 0-th element's value by 1 and now z[0] should be 0
but WHY it still returns 1 for "a" variable????
The order of your operations is this:
a = *z //*z = 1 here
*z = *z - 1 //*z = 0 here
Decrement operator happens after the assignment.
It is because the decrement operator is after the expression.
a = (*z)--;
Here first *z is evaluated and a is assigned the value (1). After that *z is decremented to zero.
If it had been
a = --(*z);
Then *z would have evaluated and decremented 1st. After that the value would have been assigned to a. Hence in this case both would be zero.
Post-decrement, thing--, yields the value before decrementing; so a is assigned the previous value of *z, which is 1.
Pre-decrement, --thing, yields the value after decrementing, so changing to a = --(*z); would set a to zero.