将 realloc 与 for 循环一起使用
我正在使用 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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
b
,而不是a
。b
元素?我不认为你是。for(count=0; count。
count
对于循环变量来说是一个糟糕的名字。count
应该保存元素的数量,而不是循环变量。j
会是什么。由于您在调用calloc
时使用它作为元素大小,因此它应该至少是 4 的倍数,即 int 的大小。这是什么?!realloc
似乎与calloc
没有任何关系。我确信还有很多其他问题。如果您需要更多帮助,则需要明确说明您的目标。
编辑
听起来你想要这样的东西:
注释:
b
, nota
.b
elements? I don't think you are.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.j
could be. Since you use it as the element size in your call tocalloc
it ought be at least be a multiple of 4, the size of in int. What is it?!realloc
doesn't seem to bear any relation to thecalloc
.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:
Notes:
代码中未初始化整数“j”,导致 a = 0 * 3,这意味着 a 将为零并且不会分配任何内存。段错误是由于您没有处理数字为 NULL 的情况。更改为并将 j 设置为有意义的值
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