Home > other >  How can I overflow this buffer in c programm using fgets?
How can I overflow this buffer in c programm using fgets?

Time:11-03

#include <stdlib.h>
 #include <unistd.h>
 #include <stdio.h>
 #include <string.h>
 int x;

 

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

 x = 0;
 puts("please enter text\n");
 fgets(buffer, 200, stdin);
 printf("You have entered: " );
 printf( buffer );
printf("\nhidden->%d",x);

 }

no matter the input it doesnt overflow it spits out text 20 length and i cant understand why,how can i overflow it (the char buffer[2])? it was compiled with

`gcc -g -O0 -mpreferred-stack-boundary=2 -m32 -fno-stack-protector -z execstack` -D_FORTIFY_SOURCE=0 test.c && mv a.out test.o

CodePudding user response:

The buffer did overflow, but maybe you didn't see it. Note that buffer is on the stack, and the overflow occurs there. The variable x isn't allocated on the stack, so there's a few chances that it is affected by the overflow.

With the code slightly modified, you'll be able to see the overflow:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    int x;
    char buffer[2];

    x = 0;
    puts("please enter text\n");
    fgets(buffer, 200, stdin);
    printf("You have entered: " );
    printf( buffer );
    printf("\nhidden->%d",x);
    return EXIT_SUCCESS;
}
  •  Tags:  
  • c
  • Related