Здравствуйте,
Возник вопрос по поводу вывода строки посредством семейства функций printf()
.
А именно: стандарт vs реализация. Что будет, если для %s
в формате printf()
передать NULL
.
Стандарт (С99, §7.19.6.1, стр. 279) говорит:
s
If nol
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.If an
l
length modifier is present, the argument shall be a pointer to the initial element of an array ofwchar_t
type. Wide characters from the array are converted to multibyte characters (each as if by a call to thewcrtomb
function, with the conversion state described by anmbstate_t
object initialized to zero before the first wide character is converted) up to and including a terminating null wide character. The resulting multibyte characters are written up to (but not including) the terminating null character (byte). If no precision is specified, the array shall contain a null wide character. If a precision is specified, no more than that many bytes are written (including shift sequences, if any), and the array shall contain a null wide character if, to equal the multibyte character sequence length given by the precision, the function would need to access a wide character one past the end of the array. In no case is a partial multibyte character written.
Т.е. «pointer to the initial element» — это неявная ссылка на разыменование указателя. А как известно, разыменование NULL вызывает UB. Но связь косвенная, и про NULL в самом описании printf ничего не сказано (sic!).
Собственно вопрос: а как на вашей libc отрабатывает следующий код:
#include <stdio.h>
#include <stdlib.h>
int main(void) { printf("%s\n", NULL); return EXIT_SUCCESS; }
Особенно интересна реализация в libc, отличных от GNU libc.