我想创建一个包含10个元素的简单整数数组。我正在使用动态内存在内存中分配空间,每当我超过该数量时,它将调用realloc以使其大小增加一倍。每当我键入“ q”时,它将退出循环并打印数组。
我知道我的程序中充满了错误,所以请引导我进入错误的地方。
/* Simple example of dynamic memory allocation */
/* When array reaches 10 elements, it calls
realloc to double the memory space available */
#include <stdio.h>
#include <stdlib.h>
#define SIZE_ARRAY 10
int main()
{
int *a;
int length=0,i=0,ch;
a= calloc(SIZE_ARRAY, sizeof(int));
if(a == NULL)
{
printf("Not enough space. Allocation failed.\n");
exit(0);
}
printf("Fill up your array: ");
while(1)
{
scanf("%d",&ch);
if(ch == 'q') //possible mistake here
break;
a[length]=ch;
length++;
if(length % 10 == 0) //when length is 10, 20, 30 ..
{
printf("Calling realloc to double size.\n");
a=realloc(a, 2*SIZE_ARRAY*sizeof(int));
}
}
printf("You array is: \n");
for(;i<length;i++)
printf("%d ",a[i]);
return 0;
}
每当我键入“ q”时,程序就会崩溃。我是一个初学者,所以我知道我在犯一个愚蠢的错误。任何帮助将不胜感激。
您不应该将每realloc()
一个可能变得非常大,非常快的内存加倍。通常,您仅以小块形式扩展内存。realloc()
如果旧的内存不能足够长的话,它也有讨厌的习惯来使用内存的另一部分。如果失败,则将旧存储器中的所有数据丢失。通过使用临时指针指向新内存并在成功分配之后交换它们,可以避免这种情况。这只需要额外的指针(最多4个或8个字节)和一个交换(最多只需要几个CPU周期)就可以了。要小心x86,xchg
它在多个处理器的情况下会使用锁,这是非常昂贵的!)
#include <stdio.h>
#include <stdlib.h>
// would normally be some small power of two, like
// e.g.: 64 or 256
#define REALLOC_GROW 10
int main()
{
// a needs to be NULL to avoid a first malloc()
int *a = NULL, *cp;
// to avoid complications allocated is int instead of size_t
int allocated = 0, length = 0, i, ch, r;
printf("Fill up your array: ");
while (1) {
// Will also do the first allocation when allocated == length
if (allocated <= length) {
// realloc() might choose another chunk of memory, so
// it is safer to work on copy here, such that nothing is lost
cp = realloc(a, (allocated + REALLOC_GROW) * sizeof(int));
if (cp == NULL) {
fprintf(stderr, "Malloc failed\n");
// but we can still use the old data
for (i = 0; i < length; i++) {
printf("%d ", a[i]);
}
// that we still have the old data means that we need to
// free that memory, too
free(a);
exit(EXIT_FAILURE);
}
a = cp;
// don't forget to keep the amount of memory we've just allocated
allocated += REALLOC_GROW;
}
// out, if user typed in anything but an integer
if ((r = scanf("%d", &ch)) != 1) {
break;
}
a[length] = ch;
length++;
}
printf("Your array is: \n");
// keep informations together, set i=0 in the loop
for (i = 0; i < length; i++) {
printf("%d ", a[i]);
}
fputc('\n', stdout);
// clean up
free(a);
exit(EXIT_SUCCESS);
}
如果你玩了一下周围用的启动值allocated
,价值REALLOC_GROW
和使用乘法,而不是加法的realloc()
和更换if(allocated <= length)
用if(1)
,你可以触发没有内存不足的错误,看看它是否仍然打印你之前输入的内容。现在,通过a
直接使用更改复制时的重新分配,并查看它是否打印数据。情况仍然可能如此,但现在不再保证。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句