0

I was playing around with memmove and I understand how it works. But whenever the end result contains more than the original source size, it prints out a bunch of random numbers. For example:

char str[] = "abcdefgh";
memmove(str + 6, str + 3, 4);
printf("%s\n", str);

gives me the output abcdefdefgbdefggh when it should give me abcdefdefg Why is the other characters being added into str?

MushSD
  • 9
  • 1
  • 7
    You wrote past the end of your buffer. This causes undefined behaviour. You used `printf("%s"` with something that is not a string, this also causes undefined behaviour. – M.M Apr 07 '16 at 03:57

2 Answers2

0
memmove(void *destination, void *source, size_t bytesToCopy)

The other characters added to the string are characters beyond the memory location of your declared char str[]. You have gone beyond the buffer address in memmove and the terminating character of '\0' has been over written. So when you call printf, the function will continue to print characters referenced by your pointer till it encounters '\0'.

Art Solano
  • 99
  • 11
0

The memory for str looks:

'a','b','c','d','e','f','g','h',0x0,?,?,?
                                 ^
                             End of buffer (terminates the string)

You copy 4 bytes from index 3 to index 6 which gives

'a','b','c','d','e','f','d','e','f','g',?,?
                                 ^
                             End of buffer

So you have

a) overwritten the string termination (0x0) by 'f'

b) written outside the buffer (i.e. 'g') which is really bad

Due to a) you'll get strange results when printing str as the string termination is gone.

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63