This week one problem was discussed by my colleague regarding memory:
Sample code 1:
int main()
{
#define Str \"This is String.\"
char dest[1
strncpy(dest, Str, sizeof(Str));
Your dest
is only one byte, so here you are writing in memory which you are not supposed to and this invokes undefined behavior. In other words, anything can happen depending on how compiler implement these things.
The most probable reason for buf
getting written is that the compiler places dest
after buf
. So when you are writing past the boundary of dest
you are writing to buf
. When you comment out buf
it leads to crash.
But as I said before, you may get completely different behavior if a different compiler or even different version of same compiler is used.
Summary: Never do anything that invokes undefined behavior. In strncpy
you are supposed to use sizeof(dest)
, not sizeof(src)
and allocate sufficient memory for destination so that data from source is not lost.