mlewis54
mlewis54

Reputation: 2380

C Array passing

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.

Upvotes: 0

Views: 100

Answers (3)

saidozcan
saidozcan

Reputation: 2215

You should allocate your array,(in main or in function)

 char *strs[128];

Upvotes: 0

cmc
cmc

Reputation: 2091

The 128 arrays in your strs[128] are not initialized/allocated.

Still, you are dereferencing them then writing datas at the addresses they actually point to, which could be anything at this point.

You could dynamically allocate them in your split function so they can fit each substring, since you are passing pointers to those pointers to your function.

Upvotes: 0

Keith Nicholas
Keith Nicholas

Reputation: 44288

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)

Upvotes: 2

Related Questions