The following C code is giving segmentation fault.
#include <stdio.h>
#include<string.h>
char *getSegment(char *symbol2,char *symbol3,char *filename) {
if (strcmp(symbol2,"static") == 0) return strcat(filename,symbol3);
}
int main() {
char *symbol2="static";
char *symbol3="asdf";
char *filename="zxcn";
printf("%s\n",getSegment(symbol2,symbol3,filename));
return 0;
}
I am trying to concatenate two strings and return the concatenated string from the function.
There is nothing wrong with your getSegment
function, per se, other than the fact that it doesn't return a valid string if the comparison is not true; rather, you are giving it an invalid third argument (the destination string).
The filename
variable is a pointer to a constant string literal of length 5 characters (the 4 visible ones plus the nul
terminator). Thus, it is: (a) not modifiable; and (b), even if it were, it is not large enough to hold the result of the concatenation.
To fix this, declare filename
as a non-constant character array that is large enough to store the result of the concatenation. In the code below, I have allowed up to 10 characters (9 plus the terminator), which is enough in your example.
To fix the first point, you need to return something in an else
clause.
#include <stdio.h>
#include<string.h>
char* getSegment(char* symbol2, char* symbol3, char* filename)
{
if (strcmp(symbol2, "static") == 0) return strcat(filename, symbol3);
else return filename; // return unmodified source string
}
int main()
{
char* symbol2 = "static";
char* symbol3 = "asdf";
char filename[10] = "zxcn"; // Both NON-CONSTANT and LARGE ENOUGH!
printf("%s\n", getSegment(symbol2, symbol3, filename));
return 0;
}
However, note that the getSegment
function here modifies the given filename
argument (which was the cause of your problem). If you want it to create a new string (from the concatenation or just a copy of the original), then you have to do the allocation of that new string yourself (and you will need to free
that memory in main
, when you're done with it).
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* getSegment(char* symbol2, char* symbol3, char* filename)
{
if (strcmp(symbol2, "static") == 0) {
char* answer = malloc(sizeof(char) * (strlen(filename) + strlen(symbol3) + 1));
strcpy(answer, filename);
strcat(answer, symbol3);
return answer;
}
else {
return strdup(filename);
}
}
int main()
{
char* symbol2 = "static";
char* symbol3 = "asdf";
char* filename = "zxcn";
char* result = getSegment(symbol2, symbol3, filename);
printf("%s\n", result);
free(result);
return 0;
}