Search code examples
ceclipsec-stringsbuffer-overflow

Eclipse C string does not overflow


I am using Eclipse IDE for C/C++ developers, while I learn about C. In theory, overflow should take place somehow when I input bigger than the size of the string I assign. But it's just all good and I cannot see the desired trouble.

int main()
{
    char nameArr[15];
    printf("Type name: ");
    scanf("%s",nameArr);
    printf("You are %s.\n",nameArr);

    return(0);
}

I wanted to intentionally see the case of overflow, but I could not. For example, when the run, if I type Wolfeschlegelsteinhausenbergerdorff, it outputs properly without any overflow-related message in Eclipse. I don't know if it is a feature of C or that of Eclipse. Does anyone know why it's fine with exceeding size?


Solution

  • As @retiredninja has mentioned in a comment, overflowing a buffer causes undefined behaviour, so you can't expect anything to happen or not happen.

    In saying that, to observe some simple buffer overflow, you can try this:

    #include <stdio.h>
    
    int main()
    {
        char overflow[16];
        char nameArr[16];
        overflow[15] = '\0';
        nameArr[15] = '\0';
        printf("Type name: ");
        scanf("%s" ,nameArr);
        printf("You are %s.\n", nameArr);
        printf("overflow: %s\n", overflow);
    
        return(0);
    }
    

    When I compile this with

    gcc -Wall -W main.c -o main -fno-stack-protector -O0
    

    and run it, I see

    $ ./main
    Type name: 123456789abcdefghijklmnopqrstuvwxyz
    You are 123456789abcdefghijklmnopqrstuvwxyz.
    overflow: hijklmnopqrstuvwxyz
    

    which shows that the extra text is written into the memory that neighbours the intended variable. The order matters here: these variables live on the stack, which grows downwards through memory, so the memory 'after' a variable belongs to the variable that was declared before it.

    Note that everything in my answer is implementation-dependent, so can not be expected to occur with all compilers, OSes, etc. This is especially true because we are talking about undefined behaviour.