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);