0

I was trying a test and I wrote this program...

#include<iostream>
using namespace std;
main()
{
    int arr[5]={1,2,3,5,3}, num=5;
    for(int i=0; i< num; i++)
    {
        for(int j=(i+1); i< num; j++)
        {
            if (arr[i]==arr[j])
            {
                cout<<"test";
            }
            cout<<j<<endl;
        }
    }
}

hmmm... In the below code I know I used "i" instead of "j",So just to create the problem I used this

for(int j=(i+1); i< num; j++)

And my problematic part of the program is-

for(int j=(i+1); i< num; j++)
        {
            if (arr[i]==arr[j])
            {
                cout<<"test";
            }
            cout<<j<<endl;
        }

in the above code when I remove this if block-

if (arr[i]==arr[j])
            {
                cout<<"test";
            }

the program goes infinite......... But when I put this if block again the program terminates automatically after some execution. I also read about this on this link but it shows example of java

And there they show the reason of negative value, but in my program there is no garbage value comes.

kNIG132103
  • 75
  • 6
  • `main()` --> `int main()` – PaulMcKenzie Feb 23 '22 at 16:47
  • 2
    You are describing what you are doing (added this, removed that, etc.) instead of posting the actual new code in its entirety, that is causing the issue. The idea of posting a [mcve] is that we don't have to follow along trying to mimic your description, and get what we have written all wrong. – PaulMcKenzie Feb 23 '22 at 16:48
  • 6
    Sooner or later `j` will be out of bounds of your array, which leads to *undefined behavior*. Undefined behavior could (but doesn't have to) lead to crashes. And a crash will make the operating system terminate the program. – Some programmer dude Feb 23 '22 at 16:48
  • What do you mean by *"the program terminates automatically after some execution"* Does code after the loop get executed? Is there no error message? Is the return code success or error? – eerorika Feb 23 '22 at 16:53
  • @eerorika no error message comes, it only prints j value. – kNIG132103 Feb 23 '22 at 16:54
  • @Someprogrammerdude okk i understood "j" will be out of bounds, but what happened to "j" when i don't use if block. – kNIG132103 Feb 23 '22 at 16:56
  • It will just increase until you get a signed integer arithmetic overflow, which *also* leads to undefined behavior. That UB will probably not crash but make the very large positive value of `j` suddenly become a very large *negative* value. Then the loop just continues. – Some programmer dude Feb 23 '22 at 17:05

4 Answers4

4

The loop condition is never false. Hence the program will continue running indefinitely.

However, with if (arr[i]==arr[j]) you access outside the bounds of arr. Hence the behaviour of the program is undefined. When the behaviour of the program is undefined, it doesn't necessarily behave as you might expect. For example, it might not continue running indefinitely.

Even without if (arr[i]==arr[j]), the loop will eventually have undefined behaviour when the loop counter overflows. But a program with undefined behaviour doesn't necessarily behave as you might not expect. For example, it might continue running indefinitely.

eerorika
  • 232,697
  • 12
  • 197
  • 326
3

Without the if (arr[i]==arr[j]), you simply have an infinite loop, which is perfectly valid in this case. j will just keep getting incremented (eventually this will overflow, which in undefined behaviour, see [basic.fundamental]/2), and the condition will never be met, since i does not change.

However, with the if (arr[i]==arr[j]) in the code, j is being incremented, and you will go outside the bounds of the array (as you know). In C++, this is Undefined Behaviour, meaning anything can happen. In your case, it seems to be causing the program to crash (which is actually a good thing, since it indicates an error).

ChrisMM
  • 8,448
  • 13
  • 29
  • 48
2

I think, the problematic part of code is

for(int j=(i+1); i< num; j++)

You are increasing j while you are checking i< num.

If you replace it with

for(int j=(i+1); j < num; j++)

it might start working.

Why it is terminating with if block, and not terminating without if block

if (arr[i]==arr[j])
{
  cout<<"test";
}

Because int have finite amount of possible values. When you reach the maximal value of int variable, the value + 1 is the smallest possible int. (As @user17732522 pointed out, the behavior might be utterly different - program crashing or something nasty happening here - because behavior of int 'overflowing' is undefined. Therefore your programs memory might be already corrupted here and it need to perform some operations to see it happened...eg. by program crash.)

Now, let's think about, what arr[i] does. arr is basically a pointer to a memory, where array begins and [i] operation is the same thing as *(arr + i).

Now, there are two possibilities what might happen

  • Program crashes when i is positive and outside of the array
  • Program crashes when i is negative

In both cases, the program crashes, because you are trying to access protected or nonexistent zone of a memory. This depends on the architecture of the system - Eg. In negative zone on 64 bit AMD64 system, you are clearly accessing nonexistent memory, if you don't have 16 exabytes of RAM. The program must in such case cause processor interruption, which is given to your OS, which kills your application.

Why it doesn't crashes when you delete the block? Nobody is trying to access the *(arr + j) and therefore, j is repeating from minimal possible value to maximal possible value without any problem.

Přemysl Šťastný
  • 1,676
  • 2
  • 18
  • 39
  • i know this. but why it is terminating with if block, and not terminating without if block. – kNIG132103 Feb 23 '22 at 16:50
  • @kNIG132103 I have added a new block of answer about the termination. – Přemysl Šťastný Feb 23 '22 at 17:04
  • @user17732522 That sounds strange to me. Can you make some reference which is saying so? - I have never programmed on other architecture then amd64 or x86, but I just don't want believe, you can't generally use int with this behavior. – Přemysl Šťastný Feb 23 '22 at 17:22
  • @user17732522 Okey. I believe you now. I will edit the answer. - 'Overflowing' the `int` was my favorite bug, so I know, how it looks in debugger. But the true is, I never used it as an intended part of program, so I never tried to optimize it...for binary operation I always use unsigned types – Přemysl Šťastný Feb 23 '22 at 17:35
  • @user17732522 Does it makes more sense now? – Přemysl Šťastný Feb 23 '22 at 17:45
0

The problem is this if statement will always be true:

for(int j=(i+1); i< num; j++){infinity}

Try setting it to this instead:

for(int j=(i+1); j< num; j++){not infinity}

You can't pass a loop on a statement that will not eventually return false or it'll go on forever.

Krausladen
  • 138
  • 10