I was actually hacking a part of code to make it useful for my purpose but I am unable to get what exactly is this statement doing :
asprintf(&buffr, "%.*s", packet_length, in + 8);
What is meant by “%.*s” specifically ??
Is it safe to use asprintf() function ??
Or using snprintf() function for the same purpose would be better and reliable ??
Thanks in advance.
The format specifier
"%.*s"is used to print a specific number of characters from achar*argument (avoids requirement for null termination). In this case,packet_lengthcharacters will be printed fromin + 8.From man asprintf():
It is safe in the sense of buffer overrun but is a non-standard function (from the linked page, it is a GNU extension). In the context of the posted code in which the size of the buffer is known prior to the
asprintf()call, theasprintf()provides a convenience for the programmer in that it avoids amalloc()(which is necessary to avoid guessing the maximum size of the buffer to be populated).If portability is not a requirement, then
snprintf()offers nothing extra thanasprintf()andasprintf()is more convenient to use.As this is tagged C++ you could use astd::stringinstead:and use
std::string::c_str()if really required. This avoids having to manuallyfree()the buffer produced byasprintf().