【问题标题】:Program crashes when calling a function from Main从 Main 调用函数时程序崩溃
【发布时间】:2015-12-06 23:39:55
【问题描述】:

这可能是一些菜鸟的错误,但我找不到。

ilasm 说我的代码生成了System.InvalidProgramException。我发现它在我调用 Fibonacci() 的那一刻被抛出 - 在调用它之前放置的标志被写入控制台,但在 .locals init 之前放置在方法中的另一个标志不是(因为异常)。

.assembly extern mscorlib { }
.assembly foo { }

.method public static int32 Fibonacci(int32 n)
{
    .locals init ([0] int32 i, [1] int32 last, [2] int32 prev)

    ldc.i4.0
    ldarg n
    brfalse done

    ldc.i4.1
    dup
    ldarg n 
    sub
    brfalse done

    ldc.i4.2
    stloc i

et1:
    dup
    stloc prev
    add
    stloc last
    ldloc prev
    ldloc last

    ldarg n
    ldloc i
    sub
    brfalse done

    ldloc i
    ldc.i4.1
    add
    stloc i
    br et1

done:
    stloc i
    pop
    ldloc i
    ret
}

.method public static void Main()
{
    .entrypoint

    ldstr "result is: {0}"
    ldstr "enter n: "
    call void [mscorlib]System.Console::Write(string)   
    call string [mscorlib]System.Console::ReadLine()    
    call int32 [mscorlib]System.Int32::Parse(string)
    call int32 Fibonacci(int32)
    box [mscorlib]System.Int32
    call void [mscorlib]System.Console::WriteLine(string,object)
    ret
}

【问题讨论】:

    标签: .net clr cil invalidprogramexception


    【解决方案1】:

    如果 n == 0 你在堆栈上使用带有 int 的 brfalse 分支。

    done 代码采用不同的堆栈布局:

    done:
        stloc i
        pop
        ldloc i
        ret
    

    看起来它假设有 2 个元素进入。

    【讨论】:

    • 哦,好吧,让我来修复它——它应该和下一个检查 n==1 的块做同样的事情。但是,是的,无论如何,崩溃是由其他原因引起的。
    • 不,这解决了它。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2017-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多