Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf : Is this safe?

Tags:

c

printf

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 ? : %.256s",my_tab); /* is it safe ? */
}
like image 506
Joze Avatar asked Oct 09 '14 15:10

Joze


People also ask

Is printf safe?

the standard C printf() and scanf() functions use stdio so they are thread-safe. the standard C printf() function is susceptible to changes in the locale settings if called in a multithreaded program.

What printf actually does?

The printf() function sends a formatted string to the standard output (the display). This string can display formatted variables and special control characters, such as new lines ('\n'), backspaces ('\b') and tabspaces ('\t'); these are listed in Table 2.1.

What can I use instead of printf?

puts() The function puts() is used to print the string on the output stream with the additional new line character '\n'. It moves the cursor to the next line. Implementation of puts() is easier than printf().

Why printf is not used in C?

The most basic printing functions would be puts and putchar which print a string and char respectively. f is for formatted. printf (unlike puts or putchar ) prints formatted output, hence printf. For example it can print an int in hexadecimal, or a float rounded to three decimal places, or a string left padded.


1 Answers

Yes, you will print out 256 characters, and nothing more.

From the C11-Standard 7.21.6. p4:

An optional precision that gives the minimum number of digits to appear for the d, i, o, u, x, and X conversions, the number of digits to appear after the decimal-point character for a, A, e, E, f, and F conversions, the maximum number of significant digits for the g and G conversions, or the maximum number of bytes to be written for s conversions. The precision takes the form of a period (.) followed either by an asterisk * (described later) or by an optional decimal integer; if only the period is specified, the precision is taken as zero. If a precision appears with any other conversion specifier, the behavior is undefined.

7.21.6.1. p8:

s : If no l length modifier is present, the argument shall be a pointer to the initial element of an array of character type. Characters from the array are written up to (but not including) the terminating null character. If the precision is specified, no more than that many bytes are written. If the precision is not specified or is greater than the size of the array, the array shall contain a null character.

like image 188
2501 Avatar answered Oct 15 '22 08:10

2501