简体   繁体   English

使用C预处理器为scanf构造字符串文字?

[英]Using C preprocessor to construct a string literal for scanf?

I'm attempting to create an sscanf string literal to aid in buffer overrun prevention in C99. 我试图创建一个sscanf字符串文字,以帮助防止C99中的缓冲区溢出。 The goal is something like: 目标是这样的:

#define MAX_ARG_LEN   16

char arg[MAX_ARG_LEN] = "";

if (sscanf(arg, "%"(MAX_ARG_LEN-1)"X", &input) > 0)

The obvious "manual" solution is something like: 显而易见的“手动”解决方案类似于:

#define MAX_ARG_LEN   16
#define MAX_ARG_CHARS "15"

char arg[MAX_ARG_LEN] = "";

if (sscanf(arg, "%"MAX_ARG_CHARS"X", &input) > 0)

However, I would prefer something to automatically generate "%15X" given a buffer size of 16. This link is almost works for my application: Convert a preprocessor token to a string but it does not handle the -1. 但是,在缓冲区大小为16的情况下,我希望自动生成“%15X”。此链接几乎适用于我的应用程序: 将预处理器令牌转换为字符串,但不处理-1。

Suggestions? 有什么建议吗?

Kernighan and Pike discuss this issue in their (excellent) book ' The Practice of Programming ' and concluded that the most reliable and portable way to do this is to use sprintf() to generate the format string. Kernighan和Pike在(出色的)《 编程实践 》一书中讨论了这个问题,并得出结论,做到这一点的最可靠和可移植的方法是使用sprintf()生成格式字符串。

What you could do is define the macro as the length excluding terminal null, and then use that like this: 您可以做的是将宏定义为不包含终端null的长度,然后像这样使用它:

#define STR_EVALUATE(x)   #x
#define STRINGIFY(x)      STR_EVALUATE(x)
#define MAX_ARG_LEN 15
char arg[MAX_ARG_LEN+1] = "";

if (sscanf(arg, "%" STRINGIFY(MAX_ARG_LEN) "X", &input) > 0)
    ...

Or you could define MAX_ARG_STRLEN as 15 and MAX_ARG_LEN as MAX_ARG_STRLEN+1 and work accordingly. 或者,您可以将MAX_ARG_STRLEN定义为15,将MAX_ARG_LEN定义为MAX_ARG_STRLEN + 1并相应地工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM