没有任何特殊原因,realloc 失败

Realloc fails without any particular reason

我正在尝试解决“假设是”一个简单的 C 问题。

问:使用 int 指针接收用户的“无限”输入,直到使用 malloc 和 realloc 接收到 EOF。

我这样定义了一个 int 指针:

int *inputBuffer = NULL;

并使用此方法对其进行初始化:

    /* #define BUFFER_SIZE 8  - already defined at top of code, posted here for more info */    
/* Creates buffer by using malloc - 
            if succeded returns true, otherwise false */
        int createBuffer(int **inputBuffer)
        {
            *inputBuffer = (int*) calloc(BUFFER_SIZE, sizeof(char)); /* Allocate memory to get input from user */
            if(*inputBuffer == NULL)    
                return FALSE;
            return TRUE;
        }

通过调用 createBuffer(&inputBuffer) 到目前为止一切顺利,内存分配成功。 在开始接收来自用户的字符之前,我定义了以下属性:

int totalCharacters = 0;
int bufferExtendsCounter = 1;
int character;

下一步是像这样接收用户输入的字符:

   /* #define MEMORY_SAFE_GAP 4  - already defined at top of code, posted here for more info */
  while((character = getchar()) != EOF && inputBuffer != NULL)
  {
        /* Check if reallocate needs to be called since almost maxed out buffer */
        if(totalCharacters - MEMORY_SAFE_GAP > (BUFFER_SIZE * bufferExtendsCounter))
        {
            /* Add 1 to extends buffer times */
            bufferExtendsCounter+=1;
            if(!extendBuffer(&inputBuffer, totalCharacters))
                printf("\nFailed to allocate more memory.");
        }       

        /* Initialize buffer with character, this is safe since there is a memory safe gap */
        inputBuffer[totalCharacters] = character;

        totalCharacters++;
  }

扩展缓冲区如下所示:

/* Extends buffer size by using realloc 
    if succeded returns true, otherwise false */
int extendBuffer(int **inputBuffer, int minimumBufferSize)
{
    /* Check how many times buffer needs to be multiple (at least) */
    int multipleBufferNumber = (minimumBufferSize / BUFFER_SIZE) + 1;
    int newBufferSize = BUFFER_SIZE * multipleBufferNumber * sizeof(char);
    while(newBufferSize < minimumBufferSize)
    {
        multipleBufferNumber+=1;
        newBufferSize = BUFFER_SIZE * multipleBufferNumber * sizeof(char);
    }
    /* Reallocate memory for next chunck of data */
    *inputBuffer = realloc(*inputBuffer, newBufferSize);
    /* Check if memory successfully allocated */
    if(*inputBuffer == NULL)
        return FALSE;
    return TRUE;
}

看来我已将缓冲区大小扩展到足以让用户输入更多内容,但仍然出现错误:

corrupted size vs. prev_size: 0x08f86010 ***

示例输入:

TestProgramTest (Pressed Enter after last 't')
(DebugPrint: Received 13 characters)
(DebugPrint: Reallocating to size 16)
*** Error in `./test': corrupted size vs. prev_size: 0x08f86010 ***

编辑(由于缺少代码部分): 以下部分紧接在 while loop:

之后
    inputBuffer[totalCharacters] = '[=17=]';
    printf("\nInput by user:\n");
/* #define LINE_LENGTH 5  - already defined at top of code, posted here for more info */
    printBuffer(inputBuffer, LINE_LENGTH, totalCharacters);
    /* free memory */
    free(inputBuffer);

并且 printBuffer 看起来像:

/* Prints the buffer data to pretty output */
void printBuffer(int *inputBuffer, int lineLength, int totalCharacters)
{
    int i;
    for(i = 0; i < totalCharacters; i++)
    {
        /* Print each char value */
        printf("%c", inputBuffer[i]);
        /* Check if got to line limit, if so enter new line */
        if((i+1) % lineLength == 0)
            printf("\n");
    }
}

第二次编辑: 将所有 int 指针部分更改为 char 指针。 完整代码如下:

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>

#define LINE_LENGTH 5
#define BUFFER_SIZE 8
#define TRUE 1
#define FALSE 0
#define MEMORY_SAFE_GAP 4

int createBuffer(char **inputBuffer);
int extendBuffer(char **inputBuffer, int minimumBufferSize);
void printBuffer(char *inputBuffer, int lineLength, int totalCharacters);

int main(void)
{
    char *inputBuffer = NULL;
    if(!createBuffer(&inputBuffer))
    {
        printf("Memory cannot be allocated, program will exit now.");
        exit(-1);
    }
    int totalCharacters = 0;
    int bufferExtendsCounter = 1;
    char character;

    printf("Please enter a string:\n");
    /* Loop till EOF received */ 
    while((character = getchar()) != EOF && inputBuffer != NULL)
    {
        /* Check if reallocate needs to be called since almost maxed out buffer */
        if(totalCharacters - MEMORY_SAFE_GAP > (BUFFER_SIZE * bufferExtendsCounter))
        {
            /* Add 1 to extends buffer times */
            bufferExtendsCounter+=1;
            if(!extendBuffer(&inputBuffer, totalCharacters))
                printf("\nFailed to allocate more memory.");
        }       

        /* Initialize buffer with character, this is safe since there is a memory safe gap */
        inputBuffer[totalCharacters] = character;

        totalCharacters++;
    }
    inputBuffer[totalCharacters] = '[=19=]';      
    printBuffer(inputBuffer, LINE_LENGTH, totalCharacters);
    /* free memory */
    free(inputBuffer);
    return 0;
}
/* Creates buffer by using malloc
    if succeded returns true, otherwise false */
int createBuffer(char **inputBuffer)
{
    /* Allocate memory to get input from user */
    *inputBuffer = (char*) calloc(BUFFER_SIZE, sizeof(char)); 
    if(*inputBuffer == NULL)    
        return FALSE;
    return TRUE;
}

/* Extends buffer size by using realloc 
    if succeded returns true, otherwise false */
int extendBuffer(char **inputBuffer, int minimumBufferSize)
{
    /* Check how many times buffer needs to be multiple (at least) */
    int multipleBufferNumber = (minimumBufferSize / BUFFER_SIZE) + 1;
    int newBufferSize = BUFFER_SIZE * multipleBufferNumber * sizeof(char);
    while(newBufferSize < minimumBufferSize)
    {
        multipleBufferNumber+=1;
        newBufferSize = BUFFER_SIZE * multipleBufferNumber * sizeof(char);
    }
    /* Reallocate memory for next chunck of data */
    *inputBuffer = realloc(*inputBuffer, newBufferSize);
    /* Check if memory successfully allocated */
    if(*inputBuffer == NULL)
        return FALSE;
    return TRUE;
}

/* Prints the buffer data to pretty output */
void printBuffer(char *inputBuffer, int lineLength, int totalCharacters)
{
    printf("Printing buffer\n");
    int i;
    for(i = 0; i < totalCharacters; i++)
    {
        /* Print each char value */
        printf("%c", inputBuffer[i]);
        /* Check if got to line limit, if so enter new line */
        if((i+1) % lineLength == 0)
            printf("\n");
    }
}

任何帮助都会很棒!

提前致谢。

就在这里

  *inputBuffer = (int*) calloc(BUFFER_SIZE, sizeof(char)); 

您为 8 个字符保留 space,但尝试在其中存储 8 个整数

为什么 inputBuffer 不只是一个 char*?因为这就是你存储的内容

现在你已经解决了 - 看看这个

if (totalCharacters  - MEMORY_SAFE_GAP > (BUFFER_SIZE * bufferExtendsCounter))

我不知道'MEMORY_SAFE_GAP'的意图是什么,但它是错误的

看看我输入8号字符后发生了什么

  if(8 - 4 > 8 * 1)

为 false,因此您不扩展缓冲区。

这个'SAFE-GAP确保你总是运行结束,如果你有

,你的代码将不再崩溃
 if (totalCharacters  >= (BUFFER_SIZE * bufferExtendsCounter))

输出仍然有点乱码,但您可以修复它。我输入1234567890得到

Please enter a string:
1234567890
^Z
Printing buffer
12345
678═0