[英]Need to avoid buffer overflow upon user entry over 8 chars above
I am trying to restrict the amount of entered chars to 8, if more is entered then the program should stop or display a msg and stop. 我试图将输入的字符数限制为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);
}
The most straightforward way is simply to check the length, and "abort" if it's too long: 最直接的方法是简单地检查长度,如果太长则“中止”:
if(strlen(argv[1]) > 7) {
printf("Argument is too long.\n");
return 1;
}
strcpy(buffer_two, argv[1]); /* copy first argument into buffer_two */
(Note that an 8-char buffer only has space for 7 characters, plus the NUL terminator) (请注意,一个8字符的缓冲区只能容纳7个字符,再加上NUL终止符)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.