Jacob Jacob - 20 days ago 6
C Question

Trying to overflow but not working as expected

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.

Answer

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.