Why is the address of two k different as shown in output of following code?
#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
using namespace std;
int anu[1000000];
int calc(int a,int b,int c,int d)
{
long long int k;
k=(long long int)a*d*d+b*d+c;
return k%1000000;
}
int main()
{
int t,n,i,a,b,c,d,k;
scanf("%d",&t);
while(t--)
{
scanf("%d %d %d %d %d",&n,&a,&b,&c,&d);
memset(anu,0,sizeof(int)*1000000);
anu[d]=1;
vector<int> anu1;
anu1.push_back(d);
for(i=1;i<n;i++)
{
k=calc(a,b,c,anu1[i-1]);
anu1.push_back(k);
anu[k]=anu[k]?0:1;
}
d=0;k=0;
printf("address of k=%d ",&k);
for(i=0;i<1000000;i++)
{
if(anu[i])
{
if(d%2)
k-=i;
else
k+=i;
d++;
}
}
printf("%d address of final k=%d\n",abs(k),&k);
}
return 0;
}
Input: 1 1 1 1 1 1
Output: Address of k=-1074414672 0 address of final k=1072693248
When I build with clang++ (with as many warnings enabled as I could) I get these warnings:
k.cpp:45:45: error: call to 'abs' is ambiguous
printf("%d address of final k=%d\n",abs(k),&k);
^~~
/usr/local/include/c++/v1/cmath:660:1: note: candidate function
abs(float __x) _NOEXCEPT {return fabsf(__x);}
^
/usr/local/include/c++/v1/cmath:664:1: note: candidate function
abs(double __x) _NOEXCEPT {return fabs(__x);}
^
/usr/local/include/c++/v1/cmath:668:1: note: candidate function
abs(long double __x) _NOEXCEPT {return fabsl(__x);}
^
This is because you don't include <cstdlib> which declares the integer version of abs. Without that include the compiler have to guess which function it should use, and it seems it chooses poorly as it picks one of the floating point variants from <cmath>. This leads to you overwriting the next argument in printf call.
When building a program, I advise everyone to enable as many warnings as possible, they usually point out things like undefined behavior as in this case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With