Home > OS >  strcat() add extra characters at the beginning
strcat() add extra characters at the beginning

Time:02-21

I would like to concatenate 2 strings in C using strcat(), but it is always add some random characters to the beginning of the new concatenated string. Could someone please tell me why is this happening and how to solve it?

This is my code:

#include "stdio.h"
#include "string.h"

int main(void)
{
  
  char text[100];
  
  strcat(text, "Line 1");
  strcat(text, "Line 2");

  printf("%s", text);
  
  return 0;
}

When I execute this I get the following output:

???    Line1Line2

I would appreciate any help.

Thank you.

CodePudding user response:

The line

strcat(text, "Line 1");

has undefined behavior, because both arguments of the strcat function call must point to strings, i.e. to null-terminated sequences of characters. However, the first argument is not guaranteed to point to a string, because text consists of indeterminate values, because it is not initialized.

You have two options to fix this bug. You can either

  • before the first call to strcat, set the first character of text to a terminating null character, i.e. text[0] = '\0';, so that text contains a valid (empty) string, or
  • replace the first function call to strcat with strcpy, because strcpy does not require that the first function argument points to a valid string.
  • Related