When input is '1 2 3 4 5 6 7 8 9 10 11' Expected output should be the same as input. Yet the output is '1 2 3 4 5 6 7 8 9 10 -1850774484' . Only happens when there are more than 10 integers being inputted. Where did I go wrong with my realloc line
当输入为'1 2 3 4 5 6 7 8 9 10 11'时预期输出应与输入相同。然而输出是'1 2 3 4 5 6 7 8 9 10 -1850774484'。仅当输入的整数超过10时才会发生。我的realloc系列在哪里出错了
#include <stdio.h>
#include <stdlib.h>
#define INITIAL_SIZE 10
int
main(int argc, char **argv){
int i = 0, num, size = 0, n = INITIAL_SIZE;
int *A;
A = malloc(n * sizeof(int));
if(A == NULL){
printf("OUT OF MEMORY\n");
exit(EXIT_FAILURE);
}
while(scanf("%d",&num) == 1 && getchar()!='\n'){
A[i] = num;
i++;
size++;
if (size >= n){
n = n * 2;
A = realloc(A,n * sizeof(int));
}
}
printf("Int Array: ");
for (i = 0; i <= size; i++){
printf("%d ", A[i]);
}
printf("\n");
return 0;
}
1 个解决方案
#1
5
There is nothing wrong with the realloc
. You are printing an extra uninitialized index in the last loop. Fix it by changing
realloc没有任何问题。您正在最后一个循环中打印一个额外的未初始化索引。通过改变来修复它
for (i = 0; i <= size; i++)
to
for (i = 0; i < size; i++)
The only problem with the realloc
is that you don't check if it was successful just like you did for the malloc
. Another problem is that you don't free the allocated memory.
realloc的唯一问题是你不会像对malloc一样检查它是否成功。另一个问题是你没有释放分配的内存。
#1
5
There is nothing wrong with the realloc
. You are printing an extra uninitialized index in the last loop. Fix it by changing
realloc没有任何问题。您正在最后一个循环中打印一个额外的未初始化索引。通过改变来修复它
for (i = 0; i <= size; i++)
to
for (i = 0; i < size; i++)
The only problem with the realloc
is that you don't check if it was successful just like you did for the malloc
. Another problem is that you don't free the allocated memory.
realloc的唯一问题是你不会像对malloc一样检查它是否成功。另一个问题是你没有释放分配的内存。