Dans le code ci-dessous, pourquoi b[9]
n'est pas initialisé au lieu de hors limites?
#include <stdio.h>
int main(void)
{
char b[] = {'N', 'i', 'c', 'e', ' ', 'y', 'o', 'u', '!'};
printf("b[9] = %d\n", b[9]);
return 0;
}
Appel du compilateur:
% gcc -O2 -W -Wall -pedantic -c foo.c
foo.c: In function ‘main':
foo.c:6:5: warning: ‘b[9]' is used uninitialized in this function [-Wuninitialized]
printf("b[9] = %d\n", b[9]);
% gcc --version
gcc (Ubuntu 5.4.0-6ubuntu1~16.04.6) 5.4.0 20160609
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Mise à jour: Maintenant, c'est étrange:
#include <stdio.h>
void foo(char *);
int main(void)
{
char b[] = {'N', 'i', 'c', 'e', ' ', 'y', 'o', 'u', '!'};
foo(&b[9]);
foo(&b[10]);
printf("b[9] = %d\n", b[9]);
printf("b[10] = %d\n", b[10]);
return 0;
}
La compilation de ces résultats donne les avertissements auxquels on peut s'attendre:
% gcc -O2 -W -Wall -pedantic -c foo.c
foo.c: In function ‘main':
foo.c:9:5: warning: array subscript is above array bounds [-Warray-bounds]
foo(&b[10]);
^
foo.c:10:29: warning: array subscript is above array bounds [-Warray-bounds]
printf("b[9] = %d\n", b[9]);
^
foo.c:11:29: warning: array subscript is above array bounds [-Warray-bounds]
printf("b[10] = %d\n", b[10]);
Soudainement, gcc voit les limites pour ce que c'est.