char* init_array()
{
const int size = 5;
char *p = (char*) malloc(size * sizeof(char));
strcpy(p, "Hello, world! How are you?");
return p;
}
with size = 5, malloc should get 5 free chars from memory, but given string does not fit into 5 chars, yet it works.
My question is why? First I thought the result would get truncated but p is the fully string, not just "Hello" or "Hell\0"
I'm using GCC on Linux. Is it related to the compiler or it is standard stuff?
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 becausestrcpy()
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
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,
should be enough to allocate space for a
size - 1
characters string.