'Size definition of strcat() function

The question is why should I define size of string (string[] should be string[some-number]) When the program is as following it gives me Abort trap: 6:

#include <stdio.h>
#include <string.h>

int main(void)
{
  char buffer1[] = "computer";
  char string[]="program";
  strcat( buffer1, string );
  printf( "buffer1 = %s\n", buffer1 );

}

This is the program from http://www.tutorialspoint.com/cprogramming/c_data_types.htm it works fine:

#include <stdio.h>
#include <string.h>

int main ()
{
   char str1[12] = "Hello";
   char str2[12] = "World";
   char str3[12];
   int  len ;

   /* copy str1 into str3 */
   strcpy(str3, str1);
   printf("strcpy( str3, str1) :  %s\n", str3 );

   /* concatenates str1 and str2 */
   strcat( str1, str2);
   printf("strcat( str1, str2):   %s\n", str1 );

   /* total lenghth of str1 after concatenation */
   len = strlen(str1);
   printf("strlen(str1) :  %d\n", len );

   return 0;
}

What is the mistake? Even if I define all of the sizes of strings in my program, my code still gives Abort trap:6?



Solution 1:[1]

From the man page of strcat:

DESCRIPTION The strcat() function appends the src string to the dest string, overwriting the termi? nating 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; buffer overruns are a favorite avenue for attacking secure programs.

When you declare your string, the compiler allocate the size of your initial string to be 9 (resp. 8) for the buffer1 (resp. string) (includin '\0').

Thus, strcat will result in 9 - 1 + 8 (i.e. 16 bytes) but only 9 are available.

Solution 2:[2]

The first parameter of strcat is used to store the result, so it must have enough space for the concatenated string.

In your code:

char buffer1[] = "computer";

is equivalent to:

char buffer1[9] = "computer";

defines a char array with just enough space for the string "computer", but not enough space for the result.

Solution 3:[3]

char buffer1[] = "computer";

Creates a buffer big enough to hold 9 characters (strlen("Hello" + 1 byte for \0)). If you write anymore data to it what you end up with is Undefined behavior (UB). This is what happens when you do a strcat.
UB means the program might crash or show literally any behavior. You are rather lucky that a program with UB crashes because it does not need to, but if it does atleast there is a indication of something wrong in it. Most of the times programs with UB will continue running correctly and crash when you least expect or want them to.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user3160557
Solution 2 Yu Hao
Solution 3 Alok Save