Codechef giving different result on online ide than the local ide

I participated in the CodeChef July cookoff 2020 and the question with problem code KFOLD
the output on running a test case is different from that on the local ide

source code:
#include
#include <unordered_map>
using namespace std;

int main()
{
int t;
cin>>t;
while(t–)
{
int n,k;
cin>>n>>k;
char c[n];
unordered_map<char,int> mp;
cin>>c;
mp[‘0’]=0;
mp[‘1’]=0;
for(int i=0;i<n;i++)
{
mp[c[i]]++;
}
int ratio;
if(mp[‘0’]==0||mp[‘1’]==0)
{
cout<<c<<endl;
}
else
{
if(mp[‘0’]>mp[‘1’])
ratio=mp[‘0’]/mp[‘1’];
else
ratio=mp[‘1’]/mp[‘0’];
if(k%(ratio+1)==0)
{
if(mp[‘0’]>mp[‘1’])
{
string s1="",s2="";
cout<<k<<endl;
for(int j=0;j<ratio*(k/(ratio+1));j++)
{
s1=s1+“0”;
s2=“0”+s2;
}
for(int j=0;j<(k/(ratio+1));j++)
{
s1=s1+“1”;
s2=“1”+s2;
}
for(int j=0;j<n/k;j++)
{
if(j%2==0)
cout<<s1;
else
cout<<s2;
}
cout<<endl;
}
else
{
string s1="",s2="";
for(int j=0;j<ratio*(k/(ratio+1));j++)
{
s1=s1+“1”;
s2=“1”+s2;
}
for(int j=0;j<(k/(ratio+1));j++)
{
s1=s1+“0”;
s2=“0”+s2;
}
for(int j=0;j<n/k;j++)
{
if(j%2==0)
cout<<s2;
else
cout<<s1;
}
cout<<endl;
}
}
else
{
cout<<“IMPOSSIBLE\n”;
}
}
cout<<mp[‘0’]<<" "<<mp[‘1’]<<endl;

}
return 0;

}

input:
2 16 8 1111000000000000 16 4 1111000000000000

output on local ide:
8
0000001111000000
12 4
4
0001100000011000
12 4

output on CodeChef ide:
8
0000001111000000
12 4
8 <- this line has the error
0000001111000000
12 4

the line with the error prints the value of variable " k " in the code.

please help.

Please either format your code or (better!) link to your submission - the forum software has mangled it and it won’t compile! :slight_smile:

Edit:

You’ve got Undefined Behaviour here:

        char c[n]; 
...
        cin>>c;
 

(c[n] isn’t big enough to hold n characters plus the null terminator!).

3 Likes

Thanks a lot, that worked
But is it necessary to hold the null terminator in a string?
as you can see that I am just iterating over the string till c[n-1] and it works fine on codeblocks.
https://www.codechef.com/viewsolution/37107076 is the submission link

 cin>>c;

adds a null terminator whether it’s “necessary” or not :man_shrugging: :slight_smile:

2 Likes