Hey guys,
This program gives me a nice segfault (on line 27 and if it's removed on the realloc() below that) and I can't seem to figure out why. Any help is greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
Parses parse_this for tokens using strtok() with seperators
(but doesn't alter parse_this due to internal copy) and puts
tokens into array_of_strings.
array_of_string (out): should be a NULL pointer in the beginning.
nr_of_strings (out) : contains the number of strings
parse_this (in) : string to be parsed
seperators (in) : seperators to be passed to strtok()
*/
int cexplode(char ***array_of_strings, unsigned int *nr_of_strings, const char * const parse_this, const char * const seperators) {
unsigned int loc_nr_of_strings = 0;
unsigned int n = 0;
unsigned int sepcnt = 0;
for (sepcnt = 0; sepcnt < strlen(seperators); sepcnt++) {
for (n = 0; n < strlen(parse_this); n++) {
if (parse_this[n] == seperators[sepcnt]) loc_nr_of_strings++;
}
loc_nr_of_strings++;
}
printf("DEBUG: %p | %d\n", (*array_of_strings), loc_nr_of_strings);
(*array_of_strings) = realloc((*array_of_strings), loc_nr_of_strings * sizeof(char*));
memset((*array_of_strings), 0, loc_nr_of_strings * sizeof(char*));
char *parse_this_copy = calloc(sizeof(char), strlen(parse_this) + 1);
strcpy(parse_this_copy, parse_this);
char *pch = strtok(parse_this_copy, seperators);
n = 0; //string count
while (pch != NULL) {
//allocate, copy, print, next string
(*array_of_strings)[n] = realloc((*array_of_strings)[n], strlen(pch) + 1);
memset((*array_of_strings)[n], 0, strlen(pch) + 1);
strcpy((*array_of_strings)[n], pch);
n++;
pch = strtok (NULL, seperators);
}
//loc_nr is for alloc. loc_nr can be > true nr. of strings, n is always true nr of strings.
loc_nr_of_strings = n;
(*nr_of_strings) = loc_nr_of_strings;
return 0;
}
int main(int argc, char *argv[]){
char ***restest = NULL;
char *test = "chickens\\hide\\in\\great\\numbers\\and\\eat\\brocolli\\iiiiiiiiii\\iiii\\iiiii";
unsigned int counter = 0;
cexplode(restest, &counter, test, "\\");
unsigned int i = 0;
for(i = 0; i < counter; i++){
puts(restest[i]);
}
return 0;
}
Thanks In advance,
Nick