I am just wondering if this expression is safe :
int main (void)
{
char my_tab[256];
memset(my_tab,0x61,sizeof(my_tab));
printf(\"Is it safe ? : %.2
Yes, this should be safe. Implementations that try accessing the character past the end of the buffer should be considered invalid.
Pseudocode for processing %.Ns
, where N
is a number, should look as follows:
size_t count = 0;
size_t N = ...;
char *ptr = ;
while (count < N && *ptr != '\0') {
putchar(*ptr++);
count++;
}
Note that the above code will never reference the character past N
.
One could imagine an implementation which inverts the condition of the while
loop, which would access the byte past the end of the buffer. However, such implementation would be invalid, because according to the standard it is legal for an implementation to require a null terminator only if the size is not specified, or it is greater than the number of characters that you have passed:
[7.19.6.1.8] If the precision is not specified or is greater than the size of the array, the array shall contain a null character.