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.
CodeChef: Practical coding for everyone is the submission link

 cin>>c;

adds a null terminator whether itโ€™s โ€œnecessaryโ€ or not :man_shrugging: :slight_smile:

2 Likes