snprintf 很有用,因为您可能希望分配一个更大的缓冲区然后重试,或者您可能按顺序调用它:
// cons lists as [a,b,c, ...]
if ( type == kin_cons_class() ) {
size_t offs = snprintf ( buf, max, "[" );
if ( offs >= max )
return nul_terminate ( buf, offs, max );
size_t count = depth;
kin_cons_ref_t empty = kin_cons_nil();
kin_cons_ref_t cons;
for ( cons = ref; cons != empty; cons = kin_cons_tail ( cons ) ) {
if ( count > 15 ) {
offs += snprintf ( buf + offs, max - offs, ", ..." );
break;
}
if ( cons != ref ) {
offs += snprintf ( buf + offs, max - offs, "," );
if ( offs >= max )
return nul_terminate ( buf, offs, max );
}
offs += string_repr ( buf + offs, max - offs, kin_cons_head ( cons ), depth, escape_strings );
if ( offs >= max )
return nul_terminate ( buf, offs, max );
++count;
}
if ( offs >= max )
return nul_terminate ( buf, offs, max );
offs += snprintf ( buf + offs, max - offs, "]" );
return nul_terminate ( buf, offs, max );
}
如果您继续不进行所有offs >= max 测试,则会出现缓冲区溢出并且会出现段错误。
printf 不会发生这种情况,因此检查退货不太常见。
如果您需要根据函数是否有效来更改您的行为,请检查返回值。许多标准库函数可能会失败,或者稍后会导致未定义的行为,因此您需要检查这些返回。
如果您不需要根据返回值更改行为,那么检查它是没有意义的。