Why does the following segfault?
I am using standard c99, icc compiler with unix. I can’t get this to not segfault, and I am curious why. I am not familiar with strcat/strcpy very much.
char *first = "First";
char *second = "Second";
char *both = (char *)malloc(strlen(first) + strlen(second) + 2);
strcpy(both, first);
strcat(both, " ");
strcat(both, second);
sprintf("%s %s", first, second);
The first parameter of
sprintfis a destination buffer. You have given it a constant string as a destination buffer.If you’re just trying to print out something, did you mean
printf?Otherwise, correct use would be something like:
Although,
sprintfhas been superseded bysnprintf, which is better to avoid buffer overflows.