c - Segmentation fault on calling function more then once -
running function more once cause segmentation fault , cannot figure out why. im not looking alternative ways split string.
splitx continue splitting x ammount of delimiters (be '|' or '\0') , return x or number of substrings make.
i should note have restarted coding in c after 3 years of easy javascript , php missing obvious.
int splitx(char **array, char *string, int x) { int y; int z; int index = 0; int windex = 0; for(y = 0; y < x; y++) { z = index; while(string[index] != '\0' && string[index] != '|') { index++; } char **tempptr = realloc(array, (y+1)*sizeof(char *)); if(tempptr == null) { free(array); return -3; } array = tempptr; array[y] = malloc(sizeof(char) * (index - z + 1)); windex = 0; for(; z < index; z++) { array[y][windex] = string[z]; windex++; } array[y][windex] = '\0'; if(string[index] == '\0') break; index++; } return y+1; } int main() { char **array; int array_len = splitx(array, query, 2); printf("%s %s %d\n", array[0], array[1], array_len); while(array_len > 0) { free(array[array_len-1]); array_len--; } free(array); array_len = splitx(array, "1|2\0", 2); printf("%s %s %d\n", array[0], array[1], array_len); while(array_len > 0) { free(array[array_len-1]); array_len--; } free(array); }
char **array; int array_len = splitx(array, query, 2);
this lets splitx()
use uninitialized array
, results in undefined behavior.
furthermore, c has no pass-by-reference - when write
array = tempptr;
inside function, has no visible effect outside it.
im not looking alternative ways split string.
you should be. current approach @ best non-idiomatic, has other mistakes (like returning y + 1
reason y
certainly, etc.).
you reinventing wheel: string , character searching, use strstr()
, strchr()
, strtok_r()
c standard library; duplicaitng string, use strdup()
instead of going through string manually, etc., etc...
what else:
use
size_t
sizes instead ofint
;maintain const correctness using
const char *
input strings.
char **split(const char *s, size_t *sz) { char **r = null; size_t n = 0, allocsz = 0; const char *p = s, *t = p; int end = 0; { const char *tmp = strchr(p, '|'); if (tmp == null) { p = p + strlen(p); end = 1; } else { p = tmp; } if (++n > allocsz) { if (allocsz == 0) allocsz = 4; else allocsz <<= 1; char **tmp = realloc(r, sizeof(*r) * allocsz); if (!tmp) abort(); // or whatever, handle error r = tmp; } r[n - 1] = malloc(p - t + 1); memcpy(r[n - 1], t, p - t); r[n - 1][p - t] = 0; p++; t = p; } while (!end); *sz = n; return r; }
Comments
Post a Comment