I cannot understand why i is set to 0 right after array is initialized to zero.
The program is working fine because I have reinitialized value of k to i.
But I could not find out why i becomes 0.
And why memset() is clearing the array, or setting the array to 0?
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main()
{
long long int i = 123456789;
long long int j = 987654321;
long long int cnt = 0;
int array[9] ;
int xyz, k, x, rem, se;
xyz = 0;
// printf("I = %llf", i);
for (i; (i < j) && (cnt < 100000); i++)
{
k = i;
x = 0;
for (se = 0; se <= 9; se++)
{
array[se] = 0;
}
/*************************************************/
i = k; // Here i becomes zero. Why?
/************************************************/
//memset(array, 0, 9);
while(k != 0)
{
rem = k % 10;
for(se = 0; se <= 9; se++)
{
if(rem == array[se])
{
xyz = 1;
break;
}
}
if(rem == array[se])
{
xyz = 1;
break;
}
array[x++] = rem;
k = k / 10;
}
if (xyz != 1)
{
cnt++;
// printf("Cnt = %d ", cnt);
// printf("The value i is = %lld\n", i);
// Sleep(10);
}
xyz = 0;
// printf("The value i is = %lld\n", i);
// printf("Cnt = %d \n", cnt);
fflush(stdin);
}
printf("The value i is = %lld \n", i-1);
return 0;
}
You have a buffer overflow; since the buffer is on the stack, it might be regarded as a form of Stack Overflow†.
It must be
kthat is being overwritten with the extra 0;iis assigned 0 because that’s the value ink. You invoke ‘undefined behaviour’ when you write outside the boundaries of an array, as you did here. Undefined behaviour means that anything can happen and it is OK. Sometimes, it will seem to work; sometimes, there’ll be unexpected side effects. Avoid ‘undefined behaviour’ at all costs.The idiomatic
forloop is:Note the
<instead of<=.† There are those who would disagree. See the comments.
You also ask about the (commented out) call to
memset():The third parameter to
memset()is the size in bytes of the area of memory to be set. You are setting 9 bytes out of a total of (probably) 36 in the array, which is unlikely to be what you wanted.Here, the array is defined in the same function so it is safe and sensible to write:
If
arraywas a parameter passed to a function, that would not work correctly; you would need a different size. For example: