I was trying to use the below code to iterate on char array elements on my PC.
#include <stdio.h>
int main(int argc , char *argv[] , char* env[]){
char szBuffer[] = {'A' , 'B' , '4' , 'y' , 't' , 'A' , 'B' , '4' , 'y' , 't' };
int i;
for ( i = 0; szBuffer[i]; i++)
printf( "i = %d -------- (int)szBuffer[i] = %d --------\n", i , (int)szBuffer[i]);
return 0;
}
But expected result did not achieve. My result:
i = 0 -------- (int)szBuffer[i] = 65 --------
i = 1 -------- (int)szBuffer[i] = 66 --------
i = 2 -------- (int)szBuffer[i] = 52 --------
i = 3 -------- (int)szBuffer[i] = 121 --------
i = 4 -------- (int)szBuffer[i] = 116 --------
i = 5 -------- (int)szBuffer[i] = 65 --------
i = 6 -------- (int)szBuffer[i] = 66 --------
i = 7 -------- (int)szBuffer[i] = 52 --------
i = 8 -------- (int)szBuffer[i] = 121 --------
i = 9 -------- (int)szBuffer[i] = 116 --------
i = 10 -------- (int)szBuffer[i] = 64 --------
But online C compiler shows the rational result as I expected.
Online compiler:
i = 0 -------- (int)szBuffer[i] = 65 --------
i = 1 -------- (int)szBuffer[i] = 66 --------
i = 2 -------- (int)szBuffer[i] = 52 --------
i = 3 -------- (int)szBuffer[i] = 121 --------
i = 4 -------- (int)szBuffer[i] = 116 --------
i = 5 -------- (int)szBuffer[i] = 65 --------
i = 6 -------- (int)szBuffer[i] = 66 --------
i = 7 -------- (int)szBuffer[i] = 52 --------
i = 8 -------- (int)szBuffer[i] = 121 --------
i = 9 -------- (int)szBuffer[i] = 116 --------
So confusing for me!
How does that 10th iteration show and why always have 64(‘@’) value?
>Solution :
I guess this Undefine Behavior(UB) was caused by the stack.
You can use this code and run it on different machines and different compilers, even different options when you compile this code. You may get different results.
#include <stdio.h>
int main(){
char buf[] = {'A'};
for(int i = 0; buf[i]; i++){
printf("i: %d, buf[i]: %c\n", i, buf[i]);
}
}
bufis on the stack. If 0x00 is stored after buf, the for loop will only print once, but if it stores other valid numbers, it will continue to print. Of course, if, unfortunately, i keep increasing until it reaches an area where you don’t have read permission, it will panic.
There are some ways to avoid this UB:
- End with \0:
char buf[] = {'A', 0}; - Enhance for-loop:
for(unsigned i = 0; i < sizeof(buf)/sizeof(char);i++){...}