I have declared 2 strings i.e string1 and string2. string1 is of size 8 and string2 is of size 200. Now, I am trying to copy string2 to string1. string1 has lesser size than string2. And I am copying number of bytes which is same as size of string2. My question is why memcpy is allowing to copy more number of bytes into a location where less number of bytes are allocated ? If I print the value of string1 now, then I am getting the same value as string2. But string1 does not have that much memory to accommodate string2. I want to know the reason behind this unusual behaviour.
// C program to demonstrate working of memcpy
#include <stdio.h>
#include <string.h>
int main()
{
char str1[8] = "Hello\0";
char str2[200] = "QuizLinkssjdjufuuejjhfgyyryryyryrynshshhsjakskkk\0";
puts("str1 before memcpy ");
puts(str1);
// Copies contents of str2 to str1
memcpy(str1, str2, sizeof(str2));
puts("\nstr1 after memcpy ");
puts(str1);
return 0;
}
Below is the output.
str1 before memcpy
Hello
str1 after memcpy
QuizLinkssjdjufuuejjhfgyyryryyryrynshshhsjakskkk
C doesn't perform any kind of bounds checking on arrays. That's part of what makes it fast. That also means that it's up to the programmer to not write past the bounds of the array. If you do so, you trigger undefined behavior in your code. What you're seeing is one of the ways undefined behavior can manifest.
The solution: don't read or write past the end of an array.