TomP TomP - 12 days ago 7
C Question

Buffer overflow example with gcc

I am trying to demonstrate buffer overflow in

strcmp
funcion in C.
I have
strcpyV.c
file:

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{

char a[8];
char b[8];

// function causes buffer overflow
strcpy(b, "01234567");

// buffer overflow again
strcpy(a, "89abcdef");

printf("\nb = %s\n", b);

return 0;
}


I compile this program using gcc compiler.

gcc -o strcpyV strcpyV.c


When I do this in raspberry py B+ (Raspbian wheezy) and run:

./strcpyV


I get expected result:

b = 0123456789abcdef


But when I do this whole process in Ubuntu 16.04 result is:

b = 01234567


Is there any way how to compile code without this memory protection?

Answer

You could pack the arrays in a struct. Then the rules for struct packing would apply, which for gcc means that the char arrays will be contiguous in this case (note that b is now before a):

#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
    struct ab {
        char b[8];   
        char a[8];
    } s;

    // function causes buffer overflow
    strcpy(s.b, "01234567");

    // buffer overflow again
    strcpy(s.a, "89abcdef");

    printf("\nb = %s\n", s.b);

    return 0;
}