【发布时间】:2018-06-29 04:22:39
【问题描述】:
我正在使用 C# 开发一个项目,其中一个问题是制作一个程序,该程序接收一个堆栈并返回一个新堆栈,其中包含该堆栈中出现的数字(出现的每个数字都将在新堆栈仅一次)。
我编写了这段代码,它工作得很好,但在中间它只是停止工作,并给出了这个错误“Unhandled Exception: OutOfMemoryException”。
我想知道是什么问题?据我所知,这是因为我的程序需要的内存比我的计算机所能提供的更多。如果我错了纠正我。
有谁知道我可以做些什么来解决这个问题或者我可以如何改进我的代码来防止这个问题?
一般我可以在代码中做些什么来防止这个问题在未来发生?
提前非常感谢您。 :)
public static Stack<int> Stk(Stack<int> S)
{
int Num;
Stack<int> New = new Stack<int>();
while (!S.IsEmpty())
{
Num = S.Pop();
while (Num != 0)
{
if (!Check(New, (Num % 10)))
{
New.Push(Num % 10);
}
Console.WriteLine("Original Stack: " + New);
Num = Num / 10;
}
}
return New;
}
public static bool Check(Stack<int> S, int num)
{
Stack<int> Temp = new Stack<int>();
while (!S.IsEmpty())
{
Console.WriteLine("Stack Temp: " + Temp);
if (num == S.Top())
{
while (!Temp.IsEmpty())
{
S.Push(Temp.Top());
}
Console.WriteLine("Number found in Stack S!");
Console.WriteLine("Stack S: " + S);
return true;
}
Temp.Push(S.Pop());
}
while (!Temp.IsEmpty())
{
S.Push(Temp.Pop());
}
Console.WriteLine("Stack S: " + S);
Console.WriteLine("Number NOT found in Stack S!");
return false;
}
【问题讨论】:
-
我想知道是什么问题? Debugger Basics
-
@Debugger Basics - rene - 程序工作正常(它完成了它需要做的事情)但总是在中间它只是停止工作(冻结)并给我“未处理的异常:OutOfMemoryException”错误.
-
老实说,一个经常崩溃的程序并不是“运行良好”的真正定义。
-
@MichaelRoy - 我的错。我的意思是说它至少在运行,只是没有正确运行,没有做它应该做的事情。请原谅我的英语不好,这不是我的母语。
标签: c# exception memory out-of-memory unhandled