prap19
prap19

Reputation: 1868

What is wrong with this program?

I am trying to write a string concatenation code. I wonder what is wrong in it. Can you guyz help me out. Here is my code.

#include <stdlib.h>

void strcat1(char *s, char *t)
{
    while(*s !='\0')
        s++;

    while((*s++=*t++)!= '\0')
    {

    }

}

int main()
{
char s[]= "hello";
char t[]= "world";
strcat1(s,t);
printf("%s", s);

return 0;
}

I am getting this output on codepad.org: Disallowed system call: SYS_socketcal Here is the link: http://codepad.org/Arz6U7YA

EDIT: Will the change char *s = "Hello" and char *t= "World" in the main function make any differenvce?

Upvotes: 2

Views: 144

Answers (4)

pmg
pmg

Reputation: 108978

s has space for 6 chars (namely 'h', 'e', 'l', 'l', 'o', and '\0').

You are trying to write there 5 more characters than it can hold.

Don't do that!

Try increasing the size of s before

int main()
{
char s[11] = "hello";
/* ... */

Edit after the edit of the OP

Changing s in main to

char *s = "hello";

changes s from an array with little space to a pointer to a string literal.

String literals are not modifiable, so you can't expect your code to work with the change.

Upvotes: 8

John Bode
John Bode

Reputation: 123458

Well, the big problem is that s isn't large enough to hold the result; it's sized to hold 6 characters (5 letters plus the 0 terminator), so as soon as you start trying to append the contents of t, you overrun the buffer.

Upvotes: 3

drudru
drudru

Reputation: 5023

You are trying to append to a constant string. That memory segment is protected. Create a new buffer, concat in there, and then return that.

Upvotes: -3

aschepler
aschepler

Reputation: 72271

Buffer overflow. You cannot append to the end of array s because it was allocated with only 6 characters (5 printable and one \0).

Upvotes: 3

Related Questions