Search code examples
cmemory-managementrealloc

How to realloc properly?



I wrote a little function to return a string made from the input given to the program, it worked fine until i traded constant size for dynamic memory allocation.
After i tested with a few printf() it looks like the program crashes when realloc() is called.
Am i doing something wrong with realloc(), or is it something else?

char* get_line()
{
    size_t ptr_pos = 0, size = 50;
    int c;
    char* line = malloc(size * sizeof *line);
    char* temp;

    while((c = getchar()) != EOF)
    {
        if(++ptr_pos >= size)
        {
            size += 50;
            temp = realloc(line, size * sizeof *line); // The program crashes on this intruction.

            if(temp != NULL)
            {
                line = temp;
                printf("Reallocation success.\n");
            }
            else
            {
                printf("Reallocation error.\n");
                free(line);
                exit(1);
            }
        }

        *line++ = c;
        if(c == '\n')
            break;
    }
    if(ptr_pos == 0)
        return NULL;
    *line = '\0';

    return line - ptr_pos;
}


Thanks for your help.


Solution

  • When you call realloc, you must give it the address of the beginning of the allocated memory, the same address as was originally returned by malloc. The same is true of free.

    But you are modifying the value of line, so it is no longer pointing to the beginning of the block when realloc is called.

    That is Undefined Behaviour, so a segfault is definitely possible.