I came across a part of question in which, I am getting an output, but I need a explanation why it is true and does work?
char arr[4];
strcpy(arr,\"This is a li
The short answer why it worked (that time) is -- you got lucky. Writing beyond the end of an array is undefined behavior. Where undefined behavior is just that, undefined, it could just a easily cause a segmentation fault as it did produce output. (though generally, stack corruption is the result)
When handling character arrays in C, you are responsible to insure you have allocated sufficient storage. When you intend to use the array as a character string, you also must allocate sufficient storage for each character +1
for the nul-terminating character at the end (which is the very definition of a nul-terminated string in C).
Why did it work? Generally, when you request say char arr[4];
the compiler is only guaranteeing that you have 4-bytes allocated for arr
. However, depending on the compiler, the alignment, etc. the compiler may actually allocate whatever it uses as a minimum allocation unit to arr
. Meaning that while you have only requested 4-bytes
and are only guaranteed to have 4-usable-bytes
, the compiler may have actually set aside 8, 16, 32, 64, or 128, etc-bytes
.
Or, again, you were just lucky that arr
was the last allocation requested and nothing yet has requested or written to the memory address starting at byte-5
following arr
in memory.
The point being, you requested 4-bytes
and are only guaranteed to have 4-bytes
available. Yes it may work in that one printf
before anything else takes place in your code, but your code is wholly unreliable and you are playing Russian-Roulette with stack corruption (if it has not already taken place).
In C, the responsibility falls to you to insure your code, storage and memory use is all well-defined and that you do not wander off into the realm of undefined, because if you do, all bets are off, and your code isn't worth the bytes it is stored in.
How could you make your code well-defined? Appropriately limit and validate each required step in your code. For your snippet, you could use strncpy
instead of strcpy
and then affirmatively nul-terminate arr
before calling printf
, e.g.
char arr[4] = ""; /* initialize all values */
strncpy(arr,"This is a link", sizeof arr); /* limit copy to bytes available */
arr[sizeof arr - 1] = 0; /* affirmatively nul-terminate */
printf ("%s\n",arr);
Now, you can rely on the contents of arr
throughout the remainder of your code.