分段错误:11 [英] Segmentation fault: 11
问题描述
我正在使用以下代码完成一个非常简单的编程练习:
I'm completing a pretty easy programming excersize with the following code:
using System;
namespace Factorial
{
class MainClass
{
static int fives(int x) {
int r = 0;
while(x % 5 == 0) {
r++;
x /= 5;
}
return r;
}
static int z(int x) {
if (x == 1)
return 0;
else
return z (x-1) + fives (x);
}
public static void Main (string[] args)
{
int testCases = Convert.ToInt32 (Console.ReadLine ());
int[] xs = new int[testCases];
for (int i=0; i<testCases; i++)
xs [i] = Convert.ToInt32 (Console.ReadLine ());
foreach (int x in xs)
Console.WriteLine (z (x));
}
}
}
对于小数字似乎可以正常工作,但是对于示例中的 8735373,它会打印分段错误:11".这是否意味着由于递归进入太深而导致内存不足?是什么原因造成的?
It seems to work OK with small numbers, but with 8735373 from the example it prints "Segmentation fault: 11". Does it mean that I run out of memory because of recursion going in too deep? What causes it?
(我在 Mac 上的 Mono 2.10.8 中运行 C#.)
(I run C# in Mono 2.10.8 on a Mac.)
PS:如果有人对 excersize 本身感兴趣,这是我的最终解决方案(更加优化).>
P.S.: If anyone's interested in the excersize itself, here's my final solution (much more optimized).
推荐答案
如果问题是由大量递归引起的,则错误可能是 StackOverflowException.正如之前所说的 golergka,我很确定这是 Mono 的错误.当内存通过尝试访问不应访问的内存地址而被错误管理时,就会出现分段错误.这种类型的错误是系统错误...不是 C# 异常.我几乎可以肯定 Mono 不能很好地管理大量的内存.希望对您的研究有所帮助.
If the issue was caused by the large amount of recursion, the error would probably be a StackOverflowException. As golergka, previously stated, I'm pretty sure it's a Mono fault. A segmentation fault occurs arises when memory is being mismanaged by trying to reach memory addresses that should not be reached. This type of error is a system error... not a C# exception. I'm almost sure that Mono isn't managing memory very well with large numbers. I hope that helps you in your research.
这篇关于分段错误:11的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!