Reputation: 45
I am in Part 2 on working with the language which basically is about memory and strings. I want to make a function similar to strcat()
in C, so here is what I have so far:
#include <stdio.h>
#include <string.h>
char *add_str(char *str, char *str2);
int main() {
char name[] = "MatthewGamer"; char name2[] = "PlayGames";
printf("%s\n", add_str(name, name2));
}
char *add_str(char str[], char str2[]) {
return strcat(str, str2);
}
Not that I want to change what's inside my function, but rather a problem after string concatenation. When I ran the program, here is what appeared:
~/BPML/C/Phase2/ $ make add_str
clang -ggdb3 -O0 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wshadow add_str.c -lcrypt -lcs50 -lm -o add_str
~/BPML/C/Phase2/ $ ./add_str
MatthewGamerPlayGames
Segmentation fault
~/BPML/C/Phase2/ $
Yep, a segmentation fault is what appeared right after. I don't understand the mechanic behind it even though I already encountered one of these occurings before.
Q: If the code within the strings are the problem, how do I fix it? If not the strings, then what?
Upvotes: 0
Views: 75
Reputation: 133879
strcat
requires that the target array has a string that is already null terminated and has extra space to hold the entire concatenated string and the null terminator, otherwise the behaviour will be undefined.
The most scaling solution would be to use strlen
, malloc
and memcpy
instead of using strcat
at all:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *concatenate(const char *s1, const char *s2) {
size_t s1_len = strlen(s1);
size_t s2_len = strlen(s2);
char *ret = malloc(s1_len + s2_len + 1);
memcpy(ret, s1, s1_len);
// copy the null terminator too
memcpy(ret + s1_len, s2, s2_len + 1);
return ret;
}
int main(void) {
char *concatenated = concatenate("Hello ", "World!");
printf("%s\n", concatenate);
free(concatenated);
}
Upvotes: 1
Reputation: 67476
Because your destination string is too short and strcat wtites outside the array bounds. You need to have space there for both strings.
int main(void) {
char name[sizeof("MatthewGamer") + sizeof("PlayGames") - 1] = "MatthewGamer"; char name2[] = "PlayGames";
printf("%s\n", add_str(name, name2));
}
Upvotes: 1