The return value goes wrong if I release something else

88 Views Asked by At

I am trying to parse a query string, feeding the method with this:

char array[] = "address=NYC&port=3359&username=JDoe&password=Secret*";

Here is my code (I have included the code for these helper methods, too, because not all libraries contain them.)

typedef struct { char *key, *value; } keyValuePair_t, *keyValuePair_p;

char* strdup(const char* s) {
    size_t len = strlen(s) + 1;
    void* _new = malloc(len);
    if (_new == NULL)
        return NULL;
    return (char*)memcpy(_new, s, len);
}

char* strsep(char** stringp, const char* delim) {
    char* s;
    const char* spanp;
    int c, sc;
    char* tok;

    if ((s = *stringp) == NULL)
        return (NULL);
    for (tok = s;;) {
        c = *s++;
        spanp = delim;
        do {
            if ((sc = *spanp++) == c) {
                if (c == 0)
                    s = NULL;
                else
                    s[-1] = 0;
                *stringp = s;
                return (tok);
            }
        } while (sc != 0);
    }
}

keyValuePair_p* queryStringProcessor(const char* array) {
    char* query = strdup(array);
    char* tokens = query;
    char* p = query;
    keyValuePair_p* ret = NULL;
    unsigned char counter = 0;

    while ((p = strsep(&tokens, "&\n"))) {
        char* var = strtok(p, "="), *val = NULL;
        if (var && (val = strtok(NULL, "="))) {
            ret = (keyValuePair_p*)realloc(ret, (counter + 1)*sizeof(keyValuePair_p));
            ret[counter] = (keyValuePair_p)calloc(1, sizeof(keyValuePair_t));
            ret[counter]->key = var;
            ret[counter]->value = val;
            ++counter;
        }
    }
    free(query);
    return ret;
}

The problem is that the queryStringProcessor produces the key-value pairs fine, but when free(query) is executed, the whole key-value pair array goes bad, and I can't figure out why. I tested it in VS2022 on Windows.

0

There are 0 best solutions below