// C program to demonstrate that size_t or// any unsigned int type should be used// carefully when used in a loop
#include<stdio.h>int main(){const size_t N = 10;int a[N];
// This is finefor (size_t n = 0; n < N; ++n)a[n] = n;
// But reverse cycles are tricky for unsigned// types as can lead to infinite loopfor (size_t n = N-1; n >= 0; --n)printf("%d ", a[n]);}
OutputInfinite loop and then segmentation fault
#include <stdio.h>
int main(){const size_t value = 200;size_t i;int arr[value];
for (i = 0 ; i < value ; ++i){arr[i] = i;}
size_t size = sizeof(arr);printf("size = %zu\n", size);}
输出:size = 800
示例(不含const)
#include <stdio.h>
int main(){size_t value = 200;size_t i;int arr[value];
for (i = 0; i < value; ++i){arr[i] = i;}
size_t size = sizeof(arr);printf("size = %zu\n", size);}
const char* reverse(char *orig){size_t len = strlen(orig);char *rev = orig + len - 1;while (rev >= orig){printf("%c", *rev);rev = rev - 1; // <= See below}return rev;}
int main() {char *string = "123";printf("%c", reverse(string));}// Output: 321
0x7ff626939004 "123" // <= orig0x7ff626939006 "3" // <= rev - 1 of 30x7ff626939005 "23" // <= rev - 2 of 30x7ff626939004 "123" // <= rev - 3 of 30x7ff6aade9003 "" // <= rev is indeterminant. This can be exploited as an out of bounds bug to read memory contents that this program has no business reading.