Still the buffer overflow happens and undefined-behavior invokes when you try to put a larger character array than its given size. You will get an error during compilation with -O2 compiler flag (the last two lines clearly summarizes everything):
In file included from /usr/include/string.h:495,
from main.c:2:
In function ‘strcat’,
inlined from ‘simple_string_func’ at main.c:6:3:
/usr/include/x86_64-linux-gnu/bits/string_fortified.h:128:10: warning: ‘__builtin___strcat_chk’ writing 14 bytes into a region of size 5 overflows the destination [-Wstringop-overflow=]
128 | return __builtin___strcat_chk (__dest, __src, __bos (__dest));
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In function ‘strcat’,
inlined from ‘simple_string_func’ at main.c:6:3,
inlined from ‘main’ at main.c:12:24:
/usr/include/x86_64-linux-gnu/bits/string_fortified.h:128:10: warning: ‘__builtin___strcat_chk’ writing 14 bytes into a region of size 5 overflows the destination [-Wstringop-overflow=]
128 | return __builtin___strcat_chk (__dest, __src, __bos (__dest));
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*** buffer overflow detected ***: terminated
Aborted (core dumped)
strcat(3) documentation says:
The strcat()
function appends the src string to the dest
string,
overwriting the terminating null byte ('\0') at the end of dest
, and
then adds a terminating null byte. The strings may not overlap, and
the dest
string must have enough space for the result. If dest
is
not large enough, program behavior is unpredictable.
You can clearly see the overflow with optimization level 2, even with static char[]
live here.
Note that the attached compilation output was generated by gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0