Search code examples
crealloc

C program crashes after 2 reallocs


I'm trying to write a small C program, but it crashes once I try to realloc with new_size being 20. Every value for new_size (in the function reallocate_buffer) under 20 works perfectly. I don't understand what's happening. This is my code.

char* reallocate_buffer(char* buffer, unsigned new_size)
{
    if (!buffer)
    {
        printf("Invallid buffer pointer given!\n");
        printf("Press any key to continue...\n");
        getchar();
        exit(2);
    }
    realloc(buffer, sizeof(char) * new_size);
    printf("Realloc is done...\n");
    if (!buffer)
    {
        printf("Couldn't increase buffer size! Maybe out of memory?\n");
        printf("Press any key to continue...\n");
        getchar();
        exit(1);
    }
    return buffer;
}

char* read_input(int* text_length)
{
    unsigned bufsize = BUFFER_SIZE;
    char* buffer = malloc(sizeof(char) * BUFFER_SIZE);
    char c;
    unsigned done = 0;
    while((c = fgetc(stdin)) != EOF && c != '\n')
    {
        printf("C is now %d\n", c);
        buffer[done] = c;
        done += 1;

        if (done == bufsize)
        {
            printf("Reallocating...\n");
            printf("Buffer size was now: %d\n", bufsize);
            bufsize += 5;
            buffer = reallocate_buffer(buffer, bufsize);
            printf("Buffer size is now: %d\n", bufsize);
        }
    }

    /* Now increase size once more if necessary to place the \0 character */
    if (bufsize == done)
    {
        printf("Reallocing once more...\n");
        bufsize++;
        reallocate_buffer(buffer, bufsize);
    }

    buffer[done] = '\0';
    return buffer;
}

int main(int argc, char * argv [])
{
    printf("Please provide input:\n");
    int line_size;
    char* word = read_input(&line_size);
    printf("You provided:\n%s\n", word);
    printf("Press any key to continue...\n");
    getchar();
    free(word);
    return 0;
}

Solution

  • You have to receive the address of reallocated buffer as the return value like

    buffer = realloc(buffer, sizeof(char) * new_size);