-3

i am using visual studio 2013 for desktop and i have run time fail with the string i don't know why this isn't working.

    int main(void)
    {
         char string[MAX1] = "THANK ";
         char you[MAX2] = "u";
         strncat(string, you, 1); //without fix this line or the next one
         printMessage(string); 
         return 0;
    }

it is running only when i am putting getchar at the end. it is working with other programs like notepad++.

MAX1=7. MAX2=2.

yarden
  • 23
  • 4

1 Answers1

0

the concatenated contents of string[] (if it worked) would be THANK u'\0' I.E. 8 characters.

however, only 7 characters were allocated.

The call to strcat() will not stop, so writes beyond the bounds of the array string[]. The result is undefined behavior and can lead to a seg fault event.

However, when using the strncat() the trailing NUL byte will not be copied. so string[] is now a unterminated char array. and the call to printMessage() will not know where to stop printing characters, Again undefined behavior.

user3629249
  • 16,402
  • 1
  • 16
  • 17