0

the code written below copies string from one array to another and i have declared the both arrays as static and i have given the size of the second array as '1' while the string size which is to be copied is greater than the size i have provided to the second array,still the program is running without any error and also coping the whole sting string and displaying it. if both the arrays are static then the size of second array 't' is increasing so that the it can holds the whole string.

#include<stdio.h>
void main()
{
char c[]="hello";
char t[1];
int i;
for(i=0;c[i]!='\0';i++)
{
    t[i]=c[i];
}
t[i]='\0';
printf("%s",t);
}
L. F.
  • 19,445
  • 8
  • 48
  • 82
Dora
  • 3
  • 4
  • You have undefined behaviour because `char t[1]` cannot hold the string in `char c[]`. `t` does not and cannot increase its size, it's just a shame that the computer didn't crash right away. People sometimes wonder *why* it didn't crash. Similarly if you walk across a motorway with your eyes closed you might not cause a crash. Or you might, there is not law governing this. – Weather Vane Apr 25 '20 at 13:37
  • @weather-vane if it is a an undefined behaviour then how the code is working and producing valid output – Dora Apr 25 '20 at 13:42
  • Sorry, didn't I just explain that? Please read my comment more carefully. Undefined means, well, undefined. – Weather Vane Apr 25 '20 at 13:43
  • Appearing to work is a typical manifestation of [Undefined Behavior](https://en.wikipedia.org/wiki/Undefined_behavior). Also may I recommend getting a good [C Book](https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list). Will save you a ton of time and frustration. These are basic concepts that are explained in any decent C book. – rustyx Apr 25 '20 at 13:43
  • @RahulDora if you compile with `-fsanitize=address` with a recent GCC or Clang compiler (recent as in less than 5 years old), you will get a runtime error (`stack-buffer-overflow`). As for why undefined behavior works, it is because it is left to the compiler developers to decide what happens in case UB is encountered (and they usually choose to let the program run). – Simon Doppler Apr 25 '20 at 13:47

1 Answers1

1

then the size of second array 't' is increasing

No. The size is not increasing. You wite to the outside of the bounds of the array, and then read out of bounds and the behaviour of the program is undefined.

P.S. The program is ill-formed because main does not return int as is required.

if it is a an undefined behaviour then how the code is working and producing valid output

Because it is undefined behaviour. Any behaviour is possible when it is undefined. You cannot assume that the output wouldn't be valid because that is not guaranteed. Nothing is guaranteed when behaviour is undefined.

eerorika
  • 232,697
  • 12
  • 197
  • 326