c - 需要避免用户输入超过 8 个字符时缓冲区溢出

标签 c if-statement buffer overflow

我正在尝试将输入的字符数量限制为 8,如果更多的话 输入后,程序应停止或显示一条消息并停止。

#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
    int value = 5
    char buffer_one[8], buffer_two[8];
    strcpy(buffer_one, "one"); /* put "one" into buffer_one */
    strcpy(buffer_two, "two"); /* put "two" into buffer_two */
    printf("[BEFORE] buffer_two is at %p and contains \'%s\'\n", buffer_two);
    printf("[BEFORE] buffer_one is at %p and contains \'%s\'\n", buffer_one);
    printf("[BEFORE] value is at %p and is %d (0x%08x)\n", &value, value, value);
    printf("\n[STRNCMP] copying %d bytes into buffer_two\n\n", strlen(argv[1]));
    strcpy(buffer_two, argv[1]); /* copy first argument into buffer_two */
    printf("[AFTER] buffer_two is at %p and contains \'%s\'\n", buffer_two);
    printf("[AFTER] buffer_one is at %p and contains \'%s\'\n", buffer_one);
    printf("[AFTER] value is at %p and is %d (0x%08x)\n", &value, value, value);
}

最佳答案

最直接的方法就是检查长度,如果太长则“中止”:

if(strlen(argv[1]) > 7) {
    printf("Argument is too long.\n");
    return 1;
}
strcpy(buffer_two, argv[1]); /* copy first argument into buffer_two */

(请注意,8 个字符的缓冲区只能容纳 7 个字符,加上 NUL 终止符)

关于c - 需要避免用户输入超过 8 个字符时缓冲区溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28975932/

相关文章:

c - 尝试使用循环读取 n 个图像时出错?

ant - 如何使用 "if-else"模拟 "condition"逻辑?

C# 烦恼 - 访问 sting 之外的数据

java - 有时写入文件 block

c++ - 我如何最好地阅读 boost 序列化文件?

C 编程。仅使用数组和指针生成随机字母字符串的函数

c - 打印 inet_ntoa 函数中的段错误

c++ - Int(1digit) 到 char 没有任何功能

python - 我想根据其他 Dataframe 中的匹配值填充 Dataframe 中的值

java - 本地文件中的 RandomAccessFile.read() 是否保证读取确切的字节数?