分段错误 |计算阶乘 |超出索引
Segmentation fault | calculating factorial | Out of Index
我在网上 IDE 上解决的许多问题中都遇到了这个分段错误,但我无法完全理解这个问题并因此解决它。请帮助我。
我知道有时会由于堆栈溢出而发生,因此,我应该使用堆内存。但是要怎么做呢?
一个例子是这段寻找大数阶乘的代码
代码
// calculate factorial of really large numbers
#include<iostream>
using namespace std;
#define MAX 500
int multiply(int arr[], int x, int len)
{
int carry = 0;
int i = 0;
int temp = 0;
for(; i < len; i++)
{
// multiply each digit w the number x and store the carry to be added in the next number
temp = 0;
temp = x * arr[i] + carry;
arr[i] = (temp%10);
carry = temp/10;
}
// if end carry is also generated, even that has to be accomodated in the ans
while(carry != 0) //18 === 8 1
{
temp = carry%10;
carry /= 10;
arr[i] = temp;
len++;
i++;
}
// final length of the number is returned so that it can be printed easily
return len;
}
void factorial(int n)
{
int arr[MAX];
// The array initially contains 1
arr[0] = 1;
int arrLeng = 1;
// multiply the nth number with n+1 to obtain the factorial
for(int i = 2; i <=n; i++)
arrLeng = multiply(arr, i, arrLeng);
// print the final ans array though in reverse order
for(int i = arrLeng-1; i >= 0; i--)
cout<<arr[i];
cout<<endl;
}
int main()
{
// input the number
int n;
cin>>n;
// call the main function
factorial(n);
return 0;
}
arrLeng
突破硬编码 MAX 500 的限制。
您应该始终检查索引。它不应超过 MAX 限制。这不是栈或堆内存分配的问题。
我在网上 IDE 上解决的许多问题中都遇到了这个分段错误,但我无法完全理解这个问题并因此解决它。请帮助我。
我知道有时会由于堆栈溢出而发生,因此,我应该使用堆内存。但是要怎么做呢?
一个例子是这段寻找大数阶乘的代码
代码
// calculate factorial of really large numbers
#include<iostream>
using namespace std;
#define MAX 500
int multiply(int arr[], int x, int len)
{
int carry = 0;
int i = 0;
int temp = 0;
for(; i < len; i++)
{
// multiply each digit w the number x and store the carry to be added in the next number
temp = 0;
temp = x * arr[i] + carry;
arr[i] = (temp%10);
carry = temp/10;
}
// if end carry is also generated, even that has to be accomodated in the ans
while(carry != 0) //18 === 8 1
{
temp = carry%10;
carry /= 10;
arr[i] = temp;
len++;
i++;
}
// final length of the number is returned so that it can be printed easily
return len;
}
void factorial(int n)
{
int arr[MAX];
// The array initially contains 1
arr[0] = 1;
int arrLeng = 1;
// multiply the nth number with n+1 to obtain the factorial
for(int i = 2; i <=n; i++)
arrLeng = multiply(arr, i, arrLeng);
// print the final ans array though in reverse order
for(int i = arrLeng-1; i >= 0; i--)
cout<<arr[i];
cout<<endl;
}
int main()
{
// input the number
int n;
cin>>n;
// call the main function
factorial(n);
return 0;
}
arrLeng
突破硬编码 MAX 500 的限制。
您应该始终检查索引。它不应超过 MAX 限制。这不是栈或堆内存分配的问题。