c++ - 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?
解决方案
长根[a];
它是变长数组。这不是 C++ 标准的一部分。(但 GNU 编译器确实支持它。它是 C99 和 C11 的一部分 -可选)。不知道它是如何实现的。但无论它是什么,它都不能包含这么多长整数。
让我们做一个数学问题。假设1MB = 10**6 Bytes
一个 long int 的大小是 4 Bytes,那么100000000
longs 占用 400MB 内存。我认为它不能存储在通常为 4MB 的堆栈中。
你说你使用了 long int。int
但是在大多数编译器中,和之间没有区别long
(尽管它可能与这个问题无关)。
而足够大的数据范围会让你调用递归函数的次数过多,这可能会导致堆栈溢出。
推荐阅读
- r - 如何使用 plotly 在散点图中显示第三个变量的第二个图例?
- javascript - 将 MySQL 数据库中的 UTC 日期时间转换为没有任何库的客户端时区
- listview - Flutter ListView 与 List 中的小部件不会在应该更新时更新
- django - 将数据插入模型时Django模型的值错误
- reactjs - 通过 Passport.js 与 React 上的 3rd-party (discord) 进行身份验证在本地工作,但在 Heroku 上托管时不能
- three.js - 当我完成 udacity 的课程练习并想在 three.js 中添加阴影时遇到问题?
- php - Twig 只显示第一个数组级别
- visual-studio-code - 在 vs 代码中格式化我的 php 脚本时如何使用 `intelephense` 删除空白行?
- jquery - jquery点击事件不适用于触摸屏
- python - Python:动态地向类添加属性