使用 snprintf 避免缓冲区溢出 [英] Using snprintf to avoid buffer overruns

查看:61
本文介绍了使用 snprintf 避免缓冲区溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我像这样使用 snprintf 来避免缓冲区溢出:

I am using snprintf like this to avoid a buffer overrun:

char err_msg[32] = {0};
snprintf(err_msg, sizeof(err_msg) - 1, "[ ST_ENGINE_FAILED ]");

我添加了 -1 来为空终止符保留空间,以防字符串长度超过 32 个字节.

I added the -1 to reserve space for the null terminator in case the string is more than 32 bytes long.

我的想法是否正确?

平台:

  • 海湾合作委员会 4.4.1
  • C99

推荐答案

正如其他人所说,在这种情况下您不需要 -1.如果数组是固定大小,我会使用 strncpy 代替.它用于复制字符串 - sprintf 用于处理困难的格式化.但是,如果数组的大小未知,或者您正在尝试确定格式化字符串需要多少存储空间.这就是我真正喜欢 snprintf 的标准指定版本的地方:

As others have said, you do not need the -1 in this case. If the array is fixed size, I would use strncpy instead. It was made for copying strings - sprintf was made for doing difficult formatting. However, if the size of the array is unknown or you are trying to determine how much storage is necessary for a formatted string. This is what I really like about the Standard specified version of snprintf:

char* get_error_message(char const *msg) {
    size_t needed = snprintf(NULL, 0, "%s: %s (%d)", msg, strerror(errno), errno);
    char  *buffer = malloc(needed+1);
    sprintf(buffer, "%s: %s (%d)", msg, strerror(errno), errno);
    return buffer;
}

将此功能与 va_copy 结合使用,您可以创建非常安全的格式化字符串操作. 

Combine this feature with va_copy and you can create very safe formatted string operations.  

这篇关于使用 snprintf 避免缓冲区溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆