这段代码中 printf 和 scanf 的使用安全吗?

问题描述 投票:0回答:1
#include <stdio.h>

int main() {
    char a[12];

    int b = scanf("%11s", a);

    if (b != 1) { return 1; };

    if (printf("%s", a) > 11) {
       
        return 1;
    };

    return 0;
}

1 -

scanf
printf
在这里使用安全吗?

2 - 我是否遗漏了一些支票?我想在 c 中编写 100% 无错误的代码

3 - scanf 缓冲区溢出是唯一的问题吗?上面的代码修复了吗?

这一切的目的是为了制作一个100%安全的c代码

c printf scanf
1个回答
0
投票

是的,

scanf()
printf()
调用在这里都是安全使用的。 我不会费心检查
printf()
的返回值,但这似乎是你的要求。 不过,请务必使用宏,以避免对两个相关的数组大小和最大字段宽度进行硬编码:

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

#define LEN 11
#define str(s) str2(s)
#define str2(s) #s

int main() {
    char a[LEN+1];
    if(scanf("%" str(LEN) "s", a) != 1)
        return EXIT_FAILURE;
    if (printf("%s", a) > 11)
        return EXIT_FAILURE;
}

或者您可以考虑将

fgets()
sizeof a
一起使用,而不是以处理换行符为代价引入额外的噪音:

   #include <string.h>

   // ...

   char a[13];
   if(!fgets(a, sizeof a, stdin))
      return EXIT_FAILURE;
   a[strcspn(a, "\n")] = '\0';
© www.soinside.com 2019 - 2024. All rights reserved.