Continuing the discussion from What's wrong with this code? :
I’ve a doubt, why writing " k+= b; " on different line gives different answer? How is this possible??
{
while (k+b <= n && t[k+b] <= x)
k += b;
}
{
while (k+b <= n && t[k+b] <= x) k += b;
}
ssjgz
October 12, 2021, 11:31am
2
In this case, it doesn’t. Why do you think it does?
I run both the codes with writing k+=b; on two different lines and it gave me different answers. ( on codechef compiler)
ssjgz
October 12, 2021, 11:35am
4
The code here:
Out of bounds access:
[simon@simon-laptop][08:39:47]
[~/devel/hackerrank/otherpeoples]>./compile-latest-cpp.sh
Compiling m_vaidya-blah.cpp
Executing command:
g++ -std=c++17 m_vaidya-blah.cpp -O3 -g3 -Wall -Wextra -Wconversion -DONLINE_JUDGE -D_GLIBCXX_DEBUG -fsanitize=undefined -ftrapv
Successful
[simon@simon-laptop][08:39:50]
[~/devel/hackerrank/otherpeoples]>./a.out
m_vaidya-blah.cpp:12:33: runtime error: index 10 out of bounds for type 'int [10]'
m_vaidya-blah.cpp:12:33: runtime error…
gives an out-of-bounds access irrespective of whether k += b;
is on the same line as the while
or not. Out-of-bounds accesses are Undefined Behaviour, so you might not get the same result each time.
1 Like