Reputation: 83
I have the following program that is supposed to invert 2 strings. Ex: Str1=a Str2=b Result: ba
However I have some Bug in the code that I can't find and it doesn't allow the program to invert the strings. Can someone take a look on this?
#include<stdio.h>
#include<string.h>
/*
Return the result of appending the characters in s2 to s1.
Assumption: enough space has been allocated for s1 to store the extra
characters.
*/
char* append (char s1[ ], char s2[ ]) {
int s1len = strlen (s1);
int s2len = strlen (s2);
int k;
for (k=0; k<s2len; k++) {
s1[k+s1len] = s2[k];
}
s1[k+s1len]='\0';
return s1;
}
int main ( ) {
char str1[10];
char str2[10];
while (1) {
printf ("str1 = ");
if (!gets (str1)) {
return 0;
};
printf ("str2 = ");
if (!gets (str2)) {
return 0;
};
printf ("The result of appending str2 to str1 is %s.\n",
append (str1, str2));
}
return 0;
}
Upvotes: 0
Views: 126
Reputation: 9819
One problem you have is buffer overflow as your strings are very short; if the result string is longer than 10 bytes, your string arrays will overflow. Make them at least 80 bytes or something like that.
(Also, you shouldn't use gets()
, since gets()
doesn't check for string length, but as you're still learning, that is an issue for later).
Your append function appends s2 to s1, and you're calling append (str1, str2)
, so you won't invert the strings. Try append (str2, str1)
instead.
Upvotes: 2