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

Need to avoid buffer overflow upon user entry over 8 chars above

我正在尝试将输入的字符数限制为 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);
}

最直接的方法就是直接检查长度,"abort"如果太长:

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 个字符的缓冲区只有 space 7 个字符,加上 NUL 终止符)