-1

I am trying to overflow one buffer in to another as a laboration to learn.

   char* tmp_test = malloc(8);
   char* tmp_test2 = malloc(8);
   strcpy(tmp_test2,"ABCDEFG\n");
   strcpy(tmp_test,"abcdefghijklmnopqrstuvxyz\n" );

   printf("1th string %s" , tmp_test);
   printf("2th string %s" , tmp_test2);
   free(tmp_test);
   free(tmp_test2);

I expect the tmp_test to flow over to tmp_test2 but this does not happen.

>1th string abcdefghijklmnopqrstuvxyz
>2th string ABCDEFG
>*** Error in `./Start': munmap_chunk(): invalid pointer: 0x00000000023bf860 ***
>Aborted

I get an error on free but everything else looks okey.

Jacob
  • 371
  • 3
  • 12
  • You might want to look at the pointers themselves, to find out how much space there is between them: `printf("%p --- %p", (void*)tmp_test, (void*)tmp_test2)` – anatolyg Nov 20 '16 at 16:07

2 Answers2

1

This is most probably because you are only writing an extra 18 bytes beyond the capacity of tmp_test, and the slack space between the two blocks is obviously larger than that.

In the header of each block the C runtime stores a few pointers, (it depends on the implementation, but it may be as many as 3,) and from the error message I infer that you are on a 64-bit system, so each pointer is 8-bytes long, which means that the slack space between the two buffers may well be 24 bytes or more.

Also, when the runtime is in debug mode it allocates even more dead space between the blocks, precisely in order to aid the detection of buffer overflows.

So, try with a longer string, and eventually you will get one to overflow into the other.

You can also use a debugger to look at the memory and see how far apart in memory the two strings are, so as to figure out how much slack space there is between the two blocks without having to engage in trial and error.

If by any chance what you want to experiment with is buffer overruns, then keep in mind that they are far more common in buffers that are allocated on the stack rather than dynamically from the heap.

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
0

Your program invokes undefined behaviour. One can't expect what will happen. In this program UB is caused when you try to allocate more elements than you have allocated space for. "I expect the tmp_test to flow over to tmp_test2" - why do you expect this?

babon
  • 3,615
  • 2
  • 20
  • 20