【问题标题】:Warning: '%s' directive writing up to 2047 bytes into a region of size 56 [-Wformat-overflow=]警告:“%s”指令将最多 2047 个字节写入大小为 56 的区域 [-Wformat-overflow=]
【发布时间】:2020-11-22 23:28:44
【问题描述】:

我有一个溢出警告,但我不明白出了什么问题。我有 gcc10。

这是整个代码块。

我也尝试 char name 2048 或 1024 或 512 或 256 以及 64 - 128 每次都得到相同的警告,我几乎搜索每个 stackflow 帖子但什么都没有得到任何东西......我看不到什么?

struct stat sb;
int num1, num2;
char buf[32];
char system_cmd[64];
struct tm new_tm;

if (stat(filename, &sb) == -1)
{
    perror ("log_file_delete_old: stat");
    return;
}

if (!S_ISDIR(sb.st_mode))
{
    return;
}

new_tm = *tm_calc (NULL, -log_keep_days);
sprintf (buf, "%04d%02d%02d", new_tm.tm_year + 1900, new_tm.tm_mon + 1, new_tm.tm_mday);
num1 = atoi(buf);

struct dirent** namelist;
int n;

n = scandir (filename, &namelist, 0, alphasort);

if (n < 0)
{
    perror ("scandir");
}
else
{
    char name[MAXNAMLEN + 1];

    while (n-- > 0)
    {
        strncpy (name, namelist[n]->d_name, 255);
        name[255] = '\0';

        free (namelist[n]);

        if (*name == '.')
        {
            continue;
        }

        if (!isdigit (*name))
        {
            continue;
        }

        num2 = atoi (name);

        if (num2 <= num1)
        {
            sprintf (system_cmd, "rm -rf %s/%s", filename, name);
            system (system_cmd);

            sys_log (0, "%s: SYSTEM_CMD: %s", __FUNCTION__, system_cmd);
            fprintf (stderr, "%s: SYSTEM_CMD: %s %s:%d %s:%d\n", __FUNCTION__, system_cmd, buf, num1, name, num2);
        }
    }
}

    free (namelist);

【问题讨论】:

  • system_cmd 只有 64 字节大。 filenamename 可能会更长。
  • 请您删除所有不相关的代码。您应该发布minimal reproducible example(强调minimal),这足以重现错误(警告)。

标签: c++ gcc-warning


【解决方案1】:

感谢 Igor,问题是 system_cmd。我正在编辑 system_cmd 512 并命名 128 来解决警告。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-29
    • 2023-03-31
    • 1970-01-01
    • 2012-04-25
    • 2021-05-11
    • 2017-12-21
    • 1970-01-01
    • 2020-01-06
    相关资源
    最近更新 更多