简体   繁体   中英

C program buffer overflow issue

I have a code for which the char array size is 8. If the gcc to compile the code with -fno-stack-protector , the stack smashing detected will only be detected after the string size is 12, such as 12345678901234567890 . If I use -fstack-protector , size 9 input will cause segmentation fault as shown below. May I know why the error only be detected at size 12 String input, not other numbers?

I did try different inputs with different char array sizes, the error will be detected when the overflow size is 11 to 13 (input size - char array size).

Code:

#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;
}

在此处输入图像描述

The code does not check that i is less than the length of the array, so it has undefined behavior if user input exceeds 7 characters. Enabling compiler options for buffer overflow checking is not foolproof, not every offending access is tested. The C programmer is in charge, good practices are needed to try and avoid such problems.

Here is a modified version:

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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