Search code examples
cpointersmallocrealloc

Malloc, realloc, and returning pointers in C


So I am trying to get information from an html page. I use curl to get the html page. I then try to parse the html page and store the information I need in a character array, but I do not know what the size of the array should be. Keep in mind this is for an assignment so I won't be giving too much code, so I am supposed to dynamically allocate memory, but since I do not know what size it is, I have to keep allocating memory with realloc. Everything is fine within the function, but once it is returned, there is nothing stored within the pointer. Here is the code. Also if there is some library that would do this for me and you know about it, could you link me to it, would make my life a whole lot easier. Thank you!

char * parse(int * input)
{
    char * output = malloc(sizeof(char));
    int start = 270;
    int index = start;
    while(input[index]!='<')
    {
        output = realloc(output, (index-start+1)*sizeof(char));
        output[index-start]=input[index];
        index++;
    }
    return output;
}

Solution

  • The strchr function finds the first occurrence of its second argument in its first argument.

    So here you'd have to find a way to run strchr starting at input[start], passing it the character '<' as second argument and store the length that strchr finds. This then gives you the length that you need to allocate for output.

    • Don't forget the '\0' character at the end.
    • Use a library function to copy the string from input to output.

    Since this is an assignment, you'll probably find out the rest by yourself ...