I'm new to C and am having trouble with pointers. I've looked at guides and (at least tried) followed their advice, but still can't get my code to work.
I've got driver.c :
int main(int argc, char *argv[]) {
char *prefix = "p", *suffix = "aa";
char *result;
result = formResult(prefix, suffix);
}
And in helper.c :
char* formResult(char *prefix, char *suffix) {
char *result = strcpy(result, prefix);
result = strcat(result, suffix);
return result;
}
I keep getting "Segmentation fault (core dumped)" when I get to this call and can't figure out how to solve it. I've tried malloc with prefix and suffix, but that wouldn't work either (though I may have been doing it wrong).
Thanks.
EDIT: I've updated driver.c to be
int main(int argc, char *argv[]) {
char *prefix = malloc(15), *suffix = malloc(15);
prefix = strcpy(prefix, "p");
suffix = strcpy(suffix, "aa");
char *result = malloc(30);
printf("step0");
result = formResult(prefix, suffix);
}
And helper.c to be
char* formResult(char *prefix, char *suffix) {
printf("step1");
char *result = malloc(strlen(prefix) + strlen(suffix) + 1);
result = strcpy(result, prefix);
result = strcat(result, suffix);
return result;
}
I can get "step0" to print, but I still get a core dump without "step1" printing.