首页 > 解决方案 > Why is there runtime-error? I have already set long int

问题描述

#include <stdio.h>

long equation(long x){
  return x*x+x;
}

long BinarySearch(long arr[],long start,long end,long k){

  if(start==0 && end==0){
    return 0;
  }
  else if((end-start)<=5){
    for(int i=start;i<=end;i++){
      if(arr[i]<=k && arr[i+1]>k){
        return i;
      }
    }
  }
  else{
    long mid=(start+end)/2;
    if(arr[mid]==k){
      return mid;
    }
    else if(arr[mid]>k){
      return BinarySearch(arr,start,mid-1,k);
    }
    else{
      return BinarySearch(arr,mid+1,end,k);
    }
  }

}

int main() {

  long a;
  scanf("%ld",&a);
  long roots[a];
  for(long i=0;i<a;i++){
    roots[i]=equation(i);
  }

  printf("%ld",BinarySearch(roots,0,a-1,a));

  return 0;
}

For small numbers (under 100000000), this code works, but over 100000000, this code has runtime error. I set every variables as a long int... I used c++ tutor, it said that the step at long equation has a problem. Invalid write of size 8... Why?

标签: c++runtime-error

解决方案


长根[a];

它是变长数组。这不是 C++ 标准的一部分。(但 GNU 编译器确实支持它。它是 C99 和 C11 的一部分 -可选)。不知道它是如何实现的。但无论它是什么,它都不能包含这么多长整数。

让我们做一个数学问题。假设1MB = 10**6 Bytes一个 long int 的大小是 4 Bytes,那么100000000longs 占用 400MB 内存。我认为它不能存储在通常为 4MB 的堆栈中。

你说你使用了 long intint但是在大多数编译器中,和之间没有区别long(尽管它可能与这个问题无关)。

而足够大的数据范围会让你调用递归函数的次数过多,这可能会导致堆栈溢出


推荐阅读