函数的返回类型是静态数组的话,安全吗?解决办法
函数的返回类型是静态数组的话,安全吗?
wget源中看到如下代码:
/* N, a byte quantity, is converted to a human-readable abberviated
form a la sizes printed by `ls -lh '. The result is written to a
static buffer, a pointer to which is returned.
Unlike `with_thousand_seps ', this approximates to the nearest unit.
Quoting GNU libit: "Most people visually process strings of 3-4
digits effectively, but longer strings of digits are more prone to
misinterpretation. Hence, converting to an abbreviated form
usually improves readability. "
This intentionally uses kilobyte (KB), megabyte (MB), etc. in their
original computer science meaning of "powers of 1024 ". Powers of
1000 would be useless since Wget already displays sizes with
thousand separators. We don 't use the "*bibyte " names invented in
1998, and seldom used in practice. Wikipedia 's entry on kilobyte
discusses this in some detail. */
char *
human_readable (int n)
{
/* These suffixes are compatible with those of GNU `ls -lh '. */
static char powers[] =
{
'K ', /* kilobyte, 2^10 bytes */
'M ', /* megabyte, 2^20 bytes */
'G ', /* gigabyte, 2^30 bytes */
'T ', /* terabyte, 2^40 bytes */
'P ', /* petabyte, 2^50 bytes */
'E ', /* exabyte, 2^60 bytes */
};
static char buf[8];
int i;
/* If the quantity is smaller than 1K, just print it. */
if (n < 1024)
{
snprintf (buf, sizeof (buf), "%d ", (int) n);
return buf; /*可以这样返回静态数组?*/
}
/* Loop over powers, dividing N with 1024 in each iteration. This
wget源中看到如下代码:
/* N, a byte quantity, is converted to a human-readable abberviated
form a la sizes printed by `ls -lh '. The result is written to a
static buffer, a pointer to which is returned.
Unlike `with_thousand_seps ', this approximates to the nearest unit.
Quoting GNU libit: "Most people visually process strings of 3-4
digits effectively, but longer strings of digits are more prone to
misinterpretation. Hence, converting to an abbreviated form
usually improves readability. "
This intentionally uses kilobyte (KB), megabyte (MB), etc. in their
original computer science meaning of "powers of 1024 ". Powers of
1000 would be useless since Wget already displays sizes with
thousand separators. We don 't use the "*bibyte " names invented in
1998, and seldom used in practice. Wikipedia 's entry on kilobyte
discusses this in some detail. */
char *
human_readable (int n)
{
/* These suffixes are compatible with those of GNU `ls -lh '. */
static char powers[] =
{
'K ', /* kilobyte, 2^10 bytes */
'M ', /* megabyte, 2^20 bytes */
'G ', /* gigabyte, 2^30 bytes */
'T ', /* terabyte, 2^40 bytes */
'P ', /* petabyte, 2^50 bytes */
'E ', /* exabyte, 2^60 bytes */
};
static char buf[8];
int i;
/* If the quantity is smaller than 1K, just print it. */
if (n < 1024)
{
snprintf (buf, sizeof (buf), "%d ", (int) n);
return buf; /*可以这样返回静态数组?*/
}
/* Loop over powers, dividing N with 1024 in each iteration. This