0

I'm trying to implement a function that takes a string to parse and delimiter string as inputs, then returns a char array containing these parsed elements including empty chars if two delimiters are adjacent.

Below is my current code:

String* _split(String self, String delim) {
    char* selfCharArr = _get_value(self, NULL);
    char* delimCharArr = _get_value(delim, NULL);

    char** tokens = calloc((_length(self) + 2), sizeof(String));
    char* var;
    int index = 0;

    var = strsep(&selfCharArr, delimCharArr);
    while(var != NULL) {
        var = strsep(&selfCharArr, delimCharArr);
        tokens[index] = var;
        index++;
    }
    return (String*) tokens;
}

However, in testing I am finding that this will only return a NULL string, and I can't figure out why. No warnings or errors are produced and I've consulted the man pages.

  • Have you tried to step through the code in a debugger to see what happens? – Some programmer dude Nov 15 '19 at 10:56
  • I've not, could you recommend a good C debugger? I've just been using notepad++ to write it – Tom Clayton Nov 15 '19 at 10:58
  • How do you build your source? What environment and tools do you use for building and running? – Some programmer dude Nov 15 '19 at 11:05
  • I would add at least `assert(index < _length(self) + 2);` before `tokens[index]` as a first measure. Also, why is that you have `char **tokens` yet you allocate `calloc(..., sizeof(String))` ? I think it would be better to just `realloc` the `tokens` pointer in the loop. – KamilCuk Nov 15 '19 at 11:11
  • I'm compiling and running on MINIX 3.2.1 – Tom Clayton Nov 15 '19 at 11:13
  • @KamilCuk [`assert`](https://en.cppreference.com/w/c/error/assert) is a macro that expands to a no-op expression if `NDEBUG` is defined, which is commonly the case for release builds. It's not really good as a run-time checker, especially considering that if it fails the assertion then the program is "crashed". – Some programmer dude Nov 15 '19 at 11:16
  • @TomClayton Sorry but I don't know what compiler toolchain is used in MINIX, or what debuggers are available. It's a very uncommon platform. – Some programmer dude Nov 15 '19 at 11:18
  • On MINIX 3.2X, gdb is working , per Wikipedia. – dash-o Nov 15 '19 at 11:40
  • Have you had a look at what selfCharArr and delimCharArr are. Do any of delimCharArr appear in selfCharArr? – cup Nov 15 '19 at 11:42

0 Answers0