The code below comes from a homework assignment discussing heap-overflow exploitations, which I understand as a concept. What I don't understand is what is going on exactly with malloc and the pointers in this code example. Obviously both pointers are pointing to the same space in the heap, but why is this? Wouldn't malloc reserve the space for buf1
and then reserve another space for buf2
?
int main(int argc, const char * argv[])
{
int diff, size = 8;
char *buf1, *buf2;
buf1 = (char * )malloc(size);
buf2 = (char *)malloc(size);
diff = buf2-buf1;
memset(buf2, '2', size);
printf("BEFORE: buf2 = %s",buf2);
memset(buf1, '1', diff +3);
printf("AFTER: buf2 = %s", buf2);
return 0;
}
This code produces the output
BEFORE: buf2 = 22222222AFTER: buf2 = 11122222
Many thanks. :)
Explanation of the result
buf1
and buf2
are not pointing to the same space.
Your result can be explained as follows.
By luck the allocations gives the following memory layout:
buf1 buf2
|--------|--------|
The first memset gives
buf1 buf2
|--------|22222222|
as in it sets from the start of buf2 to the end to 2.
The second memset gives:
buf1 buf2
|11111111|11122222|
That is it sets from the start of buf1
to 3 past it's end.
Undefined behaviour
This does not seg fault as you are changing memory that is allocated to your program.
However passing buf2
to printf
in that way is invoking undefined behavior.
The reason is that printf
involked as:
printf("BEFORE: buf2 = %s",buf2);
does not have a way to know the size of buf2
so it continues until it sees the null value \0
character which your code does not add. It seems by luck you got the value immediately after buf2 happens the be the null value.
You could either add the \0
character to the end of buf2
.
Or maybe more fitting in this case you could usethe precision format specifier (that's a .
folowed by an int
value) to let printf
know how many characters to print. That would be done as so:
printf("BEFORE: buf2 = %.8s",buf2);