Gaurav Arora Gaurav Arora - 11 months ago 48
C++ Question

Bug in C++ Code: setting one variable to zero causes unrelated variable to become zero

Why does the value of variable n2 get changed to 0 in the below code after the execution of the statement arr[26]={0}; ,(I realised this while debugging)
while memset(arr,0,sizeof(arr)); works perfectly.

using namespace std;

int main()
long int n1,n2;
int count=0,flag;
int arr[26] = {0};
string box1[n1];
string box2[n2];

for(int j=0;j<n1;j++)

for(int j=0;j<n2;j++)


for(int i=0;i<n1;i++)

for(int j=0;j<n2;j++)
arr[26]={0}; // after the execution of this statement, n2 changes to 0.. WHY???
//memset(arr,0,sizeof(arr)); // If i use memset , things work correctly
cout<<n2<<endl; //n2 becomes zero
for(int k=0;k<box1[i].length();k++)

for(int k=0;k<box2[j].length();k++)

for(int k=0;k<26;k++)



return 0;

Can anyone explain what's wrong with :

arr[26] = {0};

Answer Source

You declare arr as:

int arr[26] = {0};

Which means valid indexes for it are 0-25, making 26 spots total. Then when you write to arr[26], you are actually writing outside of the array, and overwriting memory that your compiler assigned to n2.

If you want to be able to index to 26, you need to declare space for 27 ints:

int arr[27] = {0};

Also the code:

arr[26]={0}; // after the execution of this statement, n2 changes to 0.. WHY???

Only assigns to element 26 in the array. It does not zero out the entire array or anything like that. The way to zero the entire array at runtime is with arr = {0} or using the memset code you already have.