繁体   English   中英

C 程序缓冲区溢出问题

[英]C program buffer overflow issue

我有一个char数组大小为8的代码。如果gcc用-fno-stack-protector编译代码, stack smashing detected smashing只有在字符串大小为12后才会被检测到,比如12345678901234567890 如果我使用-fstack-protector ,大小为 9 的输入将导致分段错误,如下所示。 我可以知道为什么仅在大小为 12 的字符串输入时检测到错误,而不是其他数字吗?

我确实尝试了具有不同字符数组大小的不同输入,当溢出大小为 11 到 13(输入大小 - 字符数组大小)时将检测到错误。

代码:

#include <stdio.h>

int i;

void readinput()
{
    char c, buf[8]; 
    int i;

    printf("Enter a string: ");
    for (i = 0; (c = getchar()) != '\n'; i++) buf[i] = c;
    buf[i] = '\0';
    printf("string = [%s]\n", buf);
}


int main(int argc, char *argv[])
{
    readinput();
    return 0;
}

在此处输入图像描述

该代码不会检查i是否小于数组的长度,因此如果用户输入超过 7 个字符,它会出现未定义的行为。 为缓冲区溢出检查启用编译器选项并非万无一失,并非每个违规访问都经过测试。 C 程序员负责,需要良好的实践来尝试避免此类问题。

这是修改后的版本:

#include <stdio.h>

void readinput(void) {
    char buf[8]; 
    size_t i;
    int c;

    printf("Enter a string: ");
    for (i = 0; (c = getchar()) != EOF && c != '\n';) {
        if (i + 1 < sizeof(buf))
            buf[i++] = c;
    }
    buf[i] = '\0';
    printf("string = [%s]\n", buf);
}

int main(int argc, char *argv[]) {
    readinput();
    return 0;
}

暂无
暂无

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

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