简体   繁体   English

为什么重新分配每次都会失败?

[英]Why does realloc fails every time?

I have a problem in the code. 我的代码有问题。 malloc works and in the while-loop, realloc() works for the first time and when it is called the second time it always fails. malloc有效,并且在while循环中, realloc()首次有效,而第二次调用它总是失败。 The code is part of an algorithm to get the prime factors of a number. 该代码是获取数字素数的算法的一部分。

int main()
{
    int n, in, *ar, len = 0;
    scanf("%d", &n);
    ar = (int *) malloc(1 * sizeof(int));
    while(n % 2 == 0){
        ar[len] = 2;
        len++;
        ar = (int *) realloc(ar, len * sizeof(int));
        if(ar == NULL){
            printf("Error");
            return 1;
        }
        n /= 2;
    }
    return 0;
}

I tried with len initialized to 1 but it still fails. 我尝试将len初始化为1,但仍然失败。 It is strange it does not fail on the first call but it fails on the second call. 奇怪的是,它在第​​一个调用中没有失败,但是在第二个调用中失败了。 I have read other similar questions but I am a beginner and I didn`t understand. 我读过其他类似的问题,但是我是初学者,我听不懂。 Thanks in advance! 提前致谢!

Here in your program, you are accessing an array out of bounds . 在程序中, 您正在访问一个超出范围的数组 which leads to undefined behaviour. 导致不确定的行为。

initially, when len = 0 , in the while loop: 最初,当len = 0 ,在while循环中:

ar[len] = 2;  //ar[0] = 2;
len++;        //len = 1
ar = (int *) realloc(ar, len * sizeof(int));
//ar is of size 1

then in next iteration, when len = 1 然后在下一个迭代中,当len = 1

ar[1] = 2; //you cannot access ar[1] as size of `ar` is only 1.

this continues with each iteration. 每次迭代都会继续。 To avoid this do: 为避免这种情况,请执行以下操作:

//initialize len to 1
int len = 1;

and use ar[len-1] instead of ar[len] in the while loop. 并在while循环中使用ar[len-1]代替ar[len]

Have a look at this: How dangerous is it to access an array out of bounds? 看一下: 越界访问数组有多危险?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM