I’m running into a bus error trying to do a manual concatenation of two strings without library functions (school assignment). Code is as follows:
#include <stdio.h>
char *strcattest(char string1[ ], char string2[ ]);
int main() {
printf("*****STRING CONCATENATION*****\n");
printf("Hello plus Hello: %s\n", strcattest("Hello","Hello"));
printf("Hello plus Hellp: %s\n", strcattest("Hello","Hellp"));
printf("Helo plus Hello: %s\n", strcattest("Helo","Hello"));
printf("Hello plus Helo: %s\n", strcattest("Hello","Helo"));
return(0);
}
char *strcattest(char string1[ ], char string2[ ]) {
int counter = 0;
while(string1[counter]!='\0') {
counter++;
}
int str2counter = 0;
while(string2[str2counter]!='\0') {
string1[counter] = string2[str2counter];
str2counter++;
counter++;
}
string1[counter]='\0';
return string1;
}
I’ve done some research and I think I understand conceptually why this does not work. (I’m calling trying to modify a variable — string1 — that is based on a static string.) However, I’m not sure how to rectify this so that it behaves itself. I tried introducing a local variable in the strcattest function that would behave as a copy of string1 but that got the compiler yelling at me for returning a local variable from a function.
Any help is much appreciated. Thanks!
You are correct in that you are trying to modify a static (read-only) string; doing this is what the C standard terms “undefined behaviour” (which in your case manifests as a crash).
To fix this, you need to allocate a character array that you can modify. You can do this either statically (on the stack) or dynamically (using
malloc).Statically, to initialize a character array with specific content, you can do
This will initialize the character array with the string contents, copying them (note that the similar-looking
char *mystring = "Hello!";is not an array initialization, and will instead makemystringpoint to the static string). You can place that declaration either at global scope (outside of any function, not recommended unless you have a specific reason to use a global), or in yourmainmethod (then you can pass it tostrcattest).Dynamically, the declaration looks like
to get an uninitialized buffer big enough to hold 1024 characters (counting the null terminator). If you
mallocsomething, though, you have tofreeit later, or you’ll end up with a memory leak. To put something in it, doNote that
mystring = "Hello!"in this case won’t work: why not?