I am having a problem with the following code (I don’t know if the splitString function works yet since I am getting a seg fault on calling it). The code is:
#include <stdio.h>
//
// Split String
//
int splitString(char** ret,char* instr, char* fence,int max) {
char* p;
int count=0;
char* sinstr;
char* cp;
int i=0;
while(i<max) {
cp=ret[i];
p=fence;
sinstr=instr;
while(1) {
if (*p=='\0') {
*cp='\0';
instr=sinstr;
break;
}
if (*p==*sinstr) {
p++;
sinstr++;
continue;
} else {
*cp=*instr;
cp++;
instr++;
break;
}
}
i++;
}
*cp='\0';
return count;
}
int main (int argc, char* const argv[]) {
char *strs[128];
char* in="test.txt";
splitString(strs,in,".",2);
printf("fn: %s, ext: %s\n",strs[0],strs[1]);
}
Both the splitString function call and the printf get seg faults (printf gets the fault if I comment out the call to splitString).
What I am trying to do is split a string based on a substring. The function is supposed to return the substrings in the array passed as the first arg to the function. I know I am overlooking something incredibly obvious, but my C skills are very rusty. Appreciate any guidance.
of course, you are passing strs in, and it is not initialized, and splitstring is assuming the array is pointing to actual strings, but it will be whatever its initliazed to (undefined behaviour)