C编程,realloc后丢失数据

C programming, losing data after realloc

我正在尝试获取数字字符串并将其放入 int 数组中。 我不知道我会得到多少个数字,所以我需要使用动态分配。

我使用 malloc 创建了一个数组,并尝试在循环中每次按 +1 调整它的大小。

这是我的代码

void main() 
{

    char *s;
    int *polyNums;
    int count = 0;
    char *token;  
    s = gets();
    polyNums = (int *)malloc(sizeof(int));
    if (polyNums == NULL)
    {
        printf("Could not allocate required memory\n");
        exit(1);
    }
    token = strtok(s, " ");
    while (token != NULL)
    {
        polyNums[count] = *token - '0';
        count++;
        polyNums = realloc(polyNums, count+1);
        token = strtok(NULL, " ");
    }

}

我的问题是每次执行 realloc 时,所有保存的数字都消失了,如果我的字符串是 "1 2 3" 那么在循环 1 中 polyNums[0]1,但我在重新分配后在循环 2 中丢失了它。有人可以告诉我哪里出错了吗?

您没有为数组分配足够的内存。

int *polyNums;   // Holding integer!
int count = 0;
polyNums = (int *)malloc(sizeof(int)); // enough space for interger. OK!
...
while(...)
{
  polyNums[count] = *token - '0';
  count++;
  polyNums = realloc(polyNums, count+1);  // Not enough space for intergers!
  ...
}

您访问了一个包含 int 值的数组,但您只为每个元素分配了 1 个字节。 虽然您的第一个分配可以容纳第一个整数,但您可以为任何其他数字分配更少的内存。

polyNums = realloc(polyNums, (count+1)*sizeof(*polyNums));

除此之外:

  • 不要转换 malloc
  • 的 return 值
  • 不要将 realloc 的 return 值直接分配给您的指针。如果 NULL return 值,您将丢失旧数据。

您应该看看指针和资源管理,更具体地说,您应该了解什么是 deep copy 以及如何重新分配动态内存。

一般来说,你应该为新的更大的内存块定义一个临时指针,将所有旧值复制到新的内存位置,然后你可以将临时指针重新分配给初始指针,polyNums .然后您就可以安全地添加更多新数据了。