It's called undefined behavior, since it's undefined sometimes it works. Yes you can write past a memory block in c, but that's illegal because it invokes undefined behavior, the behavior is therefore not predictable and your program might or might not work.
What you expect from strcpy()
doesn't happen because strcpy()
copies as many characters as it finds before the '\0'
terminating byte, it doesn't care if the destination buffer is large enough, that's something you must be responsible about.
If you want to copy an exact number of bytes (let's say 5) you can use
memcpy(p, "Hello, this string is very large but it doesn't matter", 5);
but beware that p
is not a valid string after that, because it has no terminating '\0'
.
You also have 2 other common bad practice that new c programmers do
You don't need to cast the return value from malloc()
.
You don't need to use sizeof(char)
because it's 1 by definition.
So,
p = malloc(size);
should be enough to allocate space for a size - 1
characters string.