将 realloc 与 for 循环一起使用

发布于 2024-10-21 23:30:02 字数 1268 浏览 3 评论 0 原文

我正在使用 realloc 在运行时在动态数组中分配内存。首先,我使用 calloc 分配了一块内存,大小为随机整数 a。在我的程序中,我取了a=2。之后我想存储生成的 14 个随机值,因此我必须使用 realloc 调整内存大小。我在 for 循环中做同样的事情。对于 1 次迭代,realloc 可以工作,但之后大小不会增加,并且会发生错误“堆损坏”。我无法理解这个问题。如果可以的话,请帮助我了解问题发生的位置以及如何解决它。 多谢。 下面是我的代码:

j=j*a; //a=3
    numbers = (int*) calloc(b, j); //b=14, no of elements I want to store

    printf("Address:%p\n",numbers);
    if (numbers == NULL)
    {
        printf("No Memory Allocated\n");
    }
    else
    {
    printf("Initial array size: %d elements\n", a);
    printf("Adding %d elements\n", b);
    }



    srand( (unsigned) time( NULL ) );
    for(count = 1; count <= b ; count++)
    {


        if(i <= j)
        {

        numbers[count] = rand() % 100 + 1;
        printf( "Adding Value:%3d Address%p\n", numbers[count],numbers[count] );

           i++;

        }

        if (i > j)
        {
                printf("Increasing array size from %d bytes to %d bytes\n",j,j*a);
                j=j*a;  
                numbers = (int*) realloc(numbers,j);
                printf("Address:%p\n",numbers);
                if(numbers == NULL)
            {
                printf("No Memory allocated\n");
            }


        }

    }   

    free(numbers);

    return 0;
}

I am using realloc to allocated memory at runtime in dynamic array. Firstly, I allocated a memory with calloc with sizeof a random integer a. In my program, I have taken a=2. After that I want to store some 14 random values generated, so I have to resize the memory using realloc. I am doing the same in a for loop. FOr 1 iteration, realloc works but after that size doesnt increase and a error occurs "corruption in heap". I am not able to understand the problem. Pls help me if you can, in understanding where the problem is occuring and how to solve it.
Thanks a lot.
Below is my code:

j=j*a; //a=3
    numbers = (int*) calloc(b, j); //b=14, no of elements I want to store

    printf("Address:%p\n",numbers);
    if (numbers == NULL)
    {
        printf("No Memory Allocated\n");
    }
    else
    {
    printf("Initial array size: %d elements\n", a);
    printf("Adding %d elements\n", b);
    }



    srand( (unsigned) time( NULL ) );
    for(count = 1; count <= b ; count++)
    {


        if(i <= j)
        {

        numbers[count] = rand() % 100 + 1;
        printf( "Adding Value:%3d Address%p\n", numbers[count],numbers[count] );

           i++;

        }

        if (i > j)
        {
                printf("Increasing array size from %d bytes to %d bytes\n",j,j*a);
                j=j*a;  
                numbers = (int*) realloc(numbers,j);
                printf("Address:%p\n",numbers);
                if(numbers == NULL)
            {
                printf("No Memory allocated\n");
            }


        }

    }   

    free(numbers);

    return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夏夜暖风 2024-10-28 23:30:02
  • 初始数组长度(长度和大小不同)是 b,而不是 a
  • 添加 b 元素?我不认为你是。
  • C 中的数组是从零开始的。循环应该是 for(count=0; count
  • count 对于循环变量来说是一个糟糕的名字。 count 应该保存元素的数量,而不是循环变量。
  • 很难想象j 会是什么。由于您在调用 calloc 时使用它作为元素大小,因此它应该至少是 4 的倍数,即 int 的大小。这是什么?!
  • realloc 似乎与 calloc 没有任何关系。

我确信还有很多其他问题。如果您需要更多帮助,则需要明确说明您的目标。

编辑

听起来你想要这样的东西:

int capacity = 10;
int count = 40;
int i;

int* array = (int*)malloc(capacity*sizeof(int));
for (i=0; i<count; i++)
{
    if (i==capacity)
    {
        capacity *= 2;
        array = (int*)realloc(array, capacity*sizeof(int));
    }
    array[i] = RandomIntInRange(1, 100);
}
free(array);

注释

  1. 没有错误检查。在生产代码中,您将检查分配是否成功,如果失败,以这种方式完成的重新分配将会泄漏。但是,当您仍处于这种理解水平时,没有必要将消息与错误检查混淆。
  2. 无需阅读输入 - 您可以做到这一点。
  3. 没有写入输出 - 你可以这样做。
  • The initial array length (length and size are not the same) is b, not a.
  • Adding b elements? I don't think you are.
  • Arrays are zero-based in C. You loop should be for(count=0; count<b ; count++).
  • count is a terrible name for a loop variable. count should hold the number of elements and not be a loop variable.
  • It's hard to imagine what j could be. Since you use it as the element size in your call to calloc it ought be at least be a multiple of 4, the size of in int. What is it?!
  • The realloc doesn't seem to bear any relation to the calloc.

I'm sure there are lots of other problems. If you want more help then a clear statement of what your goal is would be required.

EDIT

It sounds like you want something like this:

int capacity = 10;
int count = 40;
int i;

int* array = (int*)malloc(capacity*sizeof(int));
for (i=0; i<count; i++)
{
    if (i==capacity)
    {
        capacity *= 2;
        array = (int*)realloc(array, capacity*sizeof(int));
    }
    array[i] = RandomIntInRange(1, 100);
}
free(array);

Notes:

  1. No error checking. In production code you would check that the allocations succeeded, and the realloc done this way would leak if it failed. But there's no point confusing the message with error checking when you are still at this level of understanding.
  2. No reading input - you can do that.
  3. No writing output - you can do that.
说不完的你爱 2024-10-28 23:30:02

代码中未初始化整数“j”,导致 a = 0 * 3,这意味着 a 将为零并且不会分配任何内存。段错误是由于您没有处理数字为 NULL 的情况。更改为并将 j 设置为有意义的值

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

void
main (int argc, char *argv[])
{
  int a = 3;
  int j = 1 * a;        //a=3
  int b = 14;
  int *numbers = calloc (b, j); //b=14, no of elements I want to store
  int count = 0, i = 0;

  printf ("Address:%p\n", numbers);
  if (numbers == NULL)
    {
      printf ("No Memory Allocated\n");
      return;
    }
  else
    {
      printf ("Initial array size: %d elements\n", a);
      printf ("Adding %d elements\n", b);
    }



  srand ((unsigned) time (NULL));
  for (count = 1; count <= b; count++)
    {
      if (i <= j)
    {
      numbers[count] = rand () % 100 + 1;
      printf ("Adding Value:%3d Address%p\n", numbers[count],
          &(numbers[count]));

      i++;

    }

      if (i > j)
    {
      printf ("Increasing array size from %d bytes to %d bytes\n", j,
          j * a);
      j = j * a;
      numbers = (int *) realloc (numbers, j);
      printf ("Address:%p\n", numbers);
      if (numbers == NULL)
        {
          printf ("No Memory allocated\n");
        }


    }

    }

  free (numbers);
}

The integer "j" is not initialized in your code, resulting in a = 0 * 3, meaning a will be zero and no memory will be allocated. The segfault is due to you not handling that numbers is NULL. Change to and set j to something meaningful

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

void
main (int argc, char *argv[])
{
  int a = 3;
  int j = 1 * a;        //a=3
  int b = 14;
  int *numbers = calloc (b, j); //b=14, no of elements I want to store
  int count = 0, i = 0;

  printf ("Address:%p\n", numbers);
  if (numbers == NULL)
    {
      printf ("No Memory Allocated\n");
      return;
    }
  else
    {
      printf ("Initial array size: %d elements\n", a);
      printf ("Adding %d elements\n", b);
    }



  srand ((unsigned) time (NULL));
  for (count = 1; count <= b; count++)
    {
      if (i <= j)
    {
      numbers[count] = rand () % 100 + 1;
      printf ("Adding Value:%3d Address%p\n", numbers[count],
          &(numbers[count]));

      i++;

    }

      if (i > j)
    {
      printf ("Increasing array size from %d bytes to %d bytes\n", j,
          j * a);
      j = j * a;
      numbers = (int *) realloc (numbers, j);
      printf ("Address:%p\n", numbers);
      if (numbers == NULL)
        {
          printf ("No Memory allocated\n");
        }


    }

    }

  free (numbers);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文