user2630165
user2630165

Reputation: 311

Finding the error in my use of the strcat function

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;
}

Upvotes: 0

Views: 136

Answers (4)

Conor Taylor
Conor Taylor

Reputation: 3108

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.

Upvotes: 1

Raju
Raju

Reputation: 1169

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

Upvotes: 0

Lidong Guo
Lidong Guo

Reputation: 2857

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

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

Upvotes: 2

Yu Hao
Yu Hao

Reputation: 122493

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.

Upvotes: 2

Related Questions