0

Please help me i can't solve this question i've got in university. I asked in our university forum and they said this clue: "what is the difference if you send a long string to strcat, or you send the string B? "

Explain what is wrong with the next program:

#include <string.h>
#include <stdio.h>
int main()
{
    char A[10];
    char B[20];
    strcpy(A, "A student");
    strcpy(B, "fail the exam");
    printf("%s\n", strcat(A, B));
    return 0;
}
rubenvb
  • 74,642
  • 33
  • 187
  • 332
user2630165
  • 311
  • 3
  • 10

4 Answers4

2

The first parameter of strcat must be large enough to contain the concatenated resulting string. So change it to :

char A[30];

or you will probably get a segmentation fault.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
2

See "A student fail the exam" is large than 10.

So at least use char A[24] instead of char A[10]

Lidong Guo
  • 2,817
  • 2
  • 19
  • 31
1

Because strcat(s,t) concatenates t to the end of s, s must be large enough to hold the new, concatenated string. It returns a pointer to the first character in s.

Conor Taylor
  • 2,998
  • 7
  • 37
  • 69
0

Array A should be large enough to hold the contents of array B other wise strcat behaviour is unpredictable, segmentation fault may occur, Application may get crash.Refer the link below. [Link]http://linux.die.net/man/3/strcat

Raju
  • 1,149
  • 1
  • 6
  • 19