I'm trying to understand very basic stack-based buffer overflow I'm running Debian wheezy on a x86_64 Macbook Pro.

I have the following unsafe program:

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

        printf("I can never execute\n");

        char buffer[512];



        return 0;

I compiled with -z execstack and -fno-stack-protector for my tests.

I have been able to launch the program through gdb, get the address of CanNeverExecute function which is never called, and overflow the buffer to replace the return address by this address. I got printed "I can never execute", which is, so far, so good.

Now I'm trying to exploit this buffer overflow by introducing shellcode in the stack. I'm currently trying directly into gdb: break in GetInputfunction, set buffer value through gdb and jump to buffer adress with jump command.

But I have a problem when setting the buffer: I have a breakpoint just after gets function, and I ran the programm with 512 a characters as input.

In gdb, I do:

(gdb) p buffer
$1 = 'a' <repeats 512 times>

The input was read without any problem, and my buffer is 512 a I then try to modify its value. If I do this:

(gdb) set var buffer=""

and try to print buffer, its length is now 511! How come??

(gdb) p buffer
$2 = '\000' <repeats 511 times>et:

And when I try to set it back to, for instance, 512 a, I get:

Too many array elements

I can set it to 511 a though, it is really that las byte that doesn't work... How come, is there a simple explanation?

1 Answer 1


GDB protects you to overflow your char array.

(gdb) p &buffer
$25 = (char (*)[512]) 0x7fffffffdfe0

To bypass this security you can either write directly the memory :

(gdb) set 0x7fffffffe1e0=0x41414141

Or cast the array as a bigger one and then set your stuff :

set {char [513]}buffer="512xA"
  • Thanks, but I wasn't trying to write in 513 A but only 512... Or is it that the last character has to be a \x00 ? Commented Jun 9, 2013 at 16:22
  • Oh sorry that was a typo. Yes of course the last character has to be a null byte, moreover GDB tried to append it for you. Given the array definition this is why writing 511 "a" worked but not 512.
    – dna
    Commented Jun 9, 2013 at 16:28
  • Ok thanks a lot! Last question: does that mean that in C, if I create char buffer[512];, I can only fill it with 511 chars as well? Commented Jun 9, 2013 at 16:34
  • You are free to fill a 512 chars buffer with 512 chars. But in GDB when using the command set buffer="A" you are filling it with a string, thus with a final null byte terminator.
    – dna
    Commented Jun 9, 2013 at 16:47
  • That makes perfect sense Commented Jun 9, 2013 at 17:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.