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?
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.
Buffer overflow. You cannot append to the end of array s
because it was allocated with only 6 characters (5 printable and one \0
).
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.
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.
精彩评论