【问题标题】:Possible to combine two strings, each with length of PATH_MAX?可以组合两个字符串,每个字符串的长度为 PATH_MAX?
【发布时间】:2021-11-14 22:54:18
【问题描述】:

我想构建一个包含完整路径的文件名的字符串。我的做法如下:

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

int main( int argc, char *argv[] ) {

    char
        fullpath[PATH_MAX],
        workdir[PATH_MAX];
      
    sprintf( workdir, "workdir/" );
    sprintf( fullpath, "%sfilename.dat", workdir);
    printf( "fullpath = %s\n", fullpath );
  
    return EXIT_SUCCESS;
  
}

编译时,我收到以下警告

warning: ‘filename.dat’ directive writing 12 bytes into a region of size between 1 and 4096 [-Wformat-overflow=]
sprintf( fullpath, "%sfilename.dat", workdir);
                      ^~~~~~~~~~~~

note: ‘sprintf’ output between 13 and 4108 bytes into a destination of size 4096
sprintf( fullpath, "%sfilename.dat", workdir);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

我是否正确理解该警告(和注释),即我可能会组合两个字符串,每个字符串都带有PATH_MAX,这会导致问题?

这是否意味着我不应该将带有 PATH_MAX 的字符串与任何其他字符串结合起来? (至少不是我这样做的那种简化方式)

【问题讨论】:

  • 使用snprintf 而不是sprintf
  • 是的,你可能会遇到麻烦。如果workdir 包含很长的路径,则可能会超出fullpath 缓冲区。这就是为什么您应该始终确保写入缓冲区的内容永远不会超过它可以容纳的内容。
  • @Cheatah 啊,不知道snprintf,非常感谢。我想这种方法是确保snprintf 不超过PATH_MAX
  • ... 你应该检查snprintf 的返回值。它是生成的字符串长度。如果这大于或等于sizeof fullpath,则生成的字符串已被截断以适合数组。
  • @Cheatah Missing s in "%filename.dat".

标签: c string printf


【解决方案1】:

sprintf( fullpath, "%sfilename.dat", workdir); 给出警告,因为workdir 可能过长,以至于连接的大小超过了fullpath 的大小

一种没有问题的字符串连接方法:使用snprintf() 并测试其结果。

int len = snprintf(fullpath, sizeof fullpath, "%sfilename.dat", workdir);
if (len < 0 || (unsigned) len >= sizeof fullpath) {
  Handle_Error();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 2017-11-19
    • 2018-03-18
    • 1970-01-01
    • 2020-08-14
    • 2014-05-08
    • 1970-01-01
    相关资源
    最近更新 更多