我正在尝试编写一个小的C程序,但是当我尝试以20为new_size进行重新分配时,它会崩溃。20以下的new_size(在reallocate_buffer函数中)每个值都可以正常工作。我不明白发生了什么。这是我的代码。

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;
}

最佳答案

您必须接收重新分配的缓冲区的地址作为返回值,例如

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

关于c - 2重新分配后,C程序崩溃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34314954/

10-13 06:59