I am not sure what is wrong with my code:
#include <stdio.h>
#include <string.h>
char* splitstr(char* str, int part, char search) {
char* out;
int i;
int result = 0;
for(i=0; str[i]!='\0'; i++) {
if(str[i] == search) {
result = 1;
break;
}
}
if(result == 0) {
if(part == 1) {
return str;
} else {
return "";
}
}
int j;
int k;
if(part == 2) {
for(j = 0; j < i; j++) {
out[j] = str[j];
}
out[j] = '\0';
} else {
for(k = 0,j = i+1; j <= strlen(str)-1; j++, k++) {
out[k] = str[j];
}
out[k] = '\0';
}
return out;
}
}
int main() {
printf("Starting program:\n");
char* str = "Hello World!";
char* a = splitstr(str, 1, ' ');
char* b = splitstr(str, 1, ' ');
printf("A is %s\n", a);
printf("B is %s\n", b);
}
It returns the following output:
Starting program:
Segmentation Fault: 11
After debugging with gdb, I have found that the error is happening on line 30 (by using breakpoints), on the first iteration of the loop, when it tries to set out[0] (out[k]) to str[6] (str[j]). Why does this trigger a segmentation fault? I am just changing one character of a string to another!
}after the statement:return out;