V
Vincenzo Mercuri
Il 19/06/2010 20.17, Luca Forlizzi ha scritto:
Hi (ciao!),
N1256 draft 6.7.8 p2 states:
"No initializer shall attempt to provide a value for an object
not contained within the entity being initialized"
The word "shall" stays both for suggestion and
the Standard hopes you won't do that.
Let's try (gcc under cygwin):
main.c:
#include <stdio.h>
int main(void){
char s[4] = "aaaaaaaa";
for(int i = 0; i < 8; i++)
putchar( s );
return 0;
}
$gcc -std=c99 main.c
main.c: In function 'main':
main.c:5: warning: initalizer-string for array of chars is too long
$./a.exe
aaaa♦ @
So, althought it compiles you are warned about a defect.
That is a severe one.
This code is completely useless and there is no
reason to exceed the array bounds unless you want your program to
crash as soon as it increases in size (or even before),
have an unpredictable behaviour, including memory access errors,
or to make it very exploits prone.
I am a bit embarassed for the silliness of my question: :-}
Is
char s[4] = "aaaaaaaa";
a constraint violation?
I think it violates 6.7.8 p2 , and both gcc and dmc diagnose it.
But H&S 5th edition says "It is not an error - [cut] - if the string
is too long for a
character array of specified size. (It is an error in C++)."
Is the book wrong?
Hi (ciao!),
N1256 draft 6.7.8 p2 states:
"No initializer shall attempt to provide a value for an object
not contained within the entity being initialized"
The word "shall" stays both for suggestion and
the Standard hopes you won't do that.
Let's try (gcc under cygwin):
main.c:
#include <stdio.h>
int main(void){
char s[4] = "aaaaaaaa";
for(int i = 0; i < 8; i++)
putchar( s );
return 0;
}
$gcc -std=c99 main.c
main.c: In function 'main':
main.c:5: warning: initalizer-string for array of chars is too long
$./a.exe
aaaa♦ @
So, althought it compiles you are warned about a defect.
That is a severe one.
This code is completely useless and there is no
reason to exceed the array bounds unless you want your program to
crash as soon as it increases in size (or even before),
have an unpredictable behaviour, including memory access errors,
or to make it very exploits prone.