Parse a GET or POST string in C This function takes a string from an HTTP POST or GET string, finds the specified variable, and allocates memory for the result and puts it in a string. The destination is given as an address of an empty pointer.

username=johndoe&amp;password=password123


Would produce:

password123


when finding variable password.

void httpString(char **dest, char *input, const char *find) {
char *start;
char *o_input = input;
const char *o_find = find;
size_t length = 0;
size_t i = 0;
while (*input) {
    if (*input == '&amp;' || input == o_input) {
        if (*input == '&amp;') {
            input++;
            if (*input == 0) {
                return;
            }
        }
        while (*input == *find) {
            if (*input == 0 || *find == 0) {
                return;
            }
            input++;
            find++;
            if (*input == '=' &amp;&amp; *find == 0) {
                input++;
                if (*input == 0) {
                    return;
                }
                start = input;
                while (*input != '&amp;' &amp;&amp; *input) {
                    input++;
                    length++;
                }
                *dest = malloc(length + 1);
                input = start;
                while (*input != '&amp;' &amp;&amp; *input) {
                    (*dest)[i] = *input;
                    input++;
                    i++;
                }
                (*dest)[i] = 0;
                return;
            }
        }
    }
    find = o_find;
    input++;
}
}


Any feedback related to how this function can be improved would be greatly appreciated. I am worried about potential edge cases where a memory access violation could occur.
The easiest way to improve this function is to use the C standard library. As it is, it's difficult to read; you can't understand what it does at a glance. And it's unnecessary difficult, because most of the building blocks are already available for free in &lt;string.h&gt;:


find a string in another string with strstr;
find a character in a string with strchr;
copy a string with strcpy or a substring with memcpy


Once you have simplified your code, you'll have more brain space to care for not so negligeable things such as testing memory allocations:

void httpString(char **dest, char *input, const char *find) {
    char* found = strstr(input, find);
    if (!found) {
        printf("find not found!");
        return;
    }
    char* assign = found + strlen(find);
    if (*assign != '=') {
        printf("ill-formed!");
        return;
    }
    char* value = assign + 1;
    char* end_value = strchr(value, '&amp;');
    if (!end_value) end_value = strchr(value, 0);
    int length = end_value - value;

    *dest = (char*) malloc(length + 1);
    if (!*dest) {
        printf("Not enough memory");
        return;
    }
    memcpy(*dest, value, length);
    (*dest)[length] = 0;
}