I’m a C beginner, today I encountered a problem that puzzled me for hours and I subtracted the clauses where the problem occurs.
I compiled it with Archlinux(gcc).
#include <stdio.h>
#define SIZE 10
int main()
{
char s[SIZE];
int i;
for (i = 0; i < SIZE; )
s[i++] = 'm';
s[i++] = '\n';
s[i] = '\0';
printf("%s/D\n", s, i);
return 0;
}
It worked without errors.
The output is mmmmmmmmmm 11.
With one line removed. s[i++] = '\n';
#include <stdio.h>
#define SIZE 10
int main()
{
char s[SIZE];
int i;
for (i = 0; i < SIZE; )
s[i++] = 'm';
s[i] = '\0';
printf("%s %d\n", s, i);
return 0;
}
The “i” became 0.
The output: mmmmmmmmmm 0
but once compiled with Cent OS(gcc).
The “i” didn’t become 0.
back to Archlinux. I entered another line. int a = i", to reference i;
#include <stdio.h>
#define SIZE 10
int main()
{
char s[SIZE];
int i;
for (i = 0; i < SIZE; )
s[i++] = 'm';
s[i] = '\0';
int a = i;
printf("%s/D\n", s, i);
return 0;
}
And this time “i” didn’t become 0.
I’m a newbie, someone please tell me what was happening?
If this is just some stupid mistake I made, please let me know and I’ll delete the post.
Thanks!
C arrays are zero-based so valid indices in your example are [0..SIZE-1]. At the end of your loop,
i==SIZE. You then write tos[SIZE]which is one element beyond the end of your array. This has undefined consequences.In your test,
&s[SIZE] == &iso you write toiin both cases. In the first case, the ascii value of'\n'happens to be what you expected foriso you don’t notice the bug. In the second case you get luckier, resetito 0 and spot the array overflow.The fix is to exit your loop one iteration sooner, leaving space for the null terminator in your char array