C随机整数中的Realloc



我在重新分配动态分配数组的内存时遇到问题。所以我想做的是:

typedef struct {
int s;
int l;
int* arr;
bool orient;
}DAC;
...
int main()
{
DAC heap = {
4, 0, (int*)malloc(4 * sizeof(int))
};
char c = 0;
int n = 0;
while (1)
{
scanf("%c", &c);
switch (c)
{
case '+':
if (heap.s == heap.l)
{
heap.s *= 2;
heap.arr = (int*)realloc(heap.arr, heap.s);
}
scanf("%dn", &(heap.arr[heap.l]));
heap.l++;
break;
case 'p':
for (int i = 0; i < heap.l; i++)
printf("%d ", heap.arr[i]);
printf("n");
break;
}
}
}

只要我的整个结构适用于n<5(我从大小为'4'的数组开始(,当执行这个块时会发生奇怪的事情:

if (heap.s==heap.l)
{
heap.s*=2;
heap.arr=(int*)realloc(heap.arr,heap.s);
}

我在数组的索引[2]处得到错误输出的原因是什么?我知道我可以用mallocs来做,只是想知道,因为我认为的情况很奇怪

整个输入/输出:

+ 1
+ 2
+ 3
+ 4
p
1 2 3 4
+ 5
p
1 2 -33686019 4 5

初始化heap:时开始更正

DAC heap = {
4, 0, (int*)malloc(4 * sizeof(int))
};

但当你真的想增加大小时,你忘记了调整整数的大小。您没有增加大小以适应8个int值,而是只得到8个字节。

正如Felix G在评论中提醒的那样,永远不应该直接分配给同一个指针。如果realloc返回NULL,则您将无法再访问旧地址。

使用这个替代:

if (heap.s == heap.l)
{
heap.s *= 2;
void *tmp = realloc(heap.arr, heap.s * sizeof(int));
if (tmp != NULL) {
heap.arr = tmp;
} else {
// handle error...
}
}

最新更新