Search code examples
vb.netstack-overflow

Stack overflow in nested loop in Visual Basic


I made a constructor in my program but it kept giving me the stack overflow exception. I tried changing parameters but it did not help...

Public Sub New()
    InitializeComponent()

    For i As Integer = 0 To i = 12
        For j As Integer = 0 To i = 9
            atomcode(i, j) = (i * 10000 + j * 1000 + 99)
        Next j
    Next i

End Sub

Solution

  • I am not sure if you tried typing your code in, or pasted your code. The format of your For statement is wrong and in the second statement you are using j and i both which if it worked would be incrementing j until i is = 9 which would cause your stackoverflow. something like this simple console program example should work. Also the only way your above code will compile is if you have Option Strict Off, do yourself a favor and place Option Strict On at the top of your Class, it will prevent implicit narrowing conversions and save you a lot of grief.

    Option Strict On
    Module Module1
        Dim atomcode(,) As Integer
    
        Sub Main()
            ReDim atomcode(12, 9)
            For i As Integer = 0 To 12
                For j As Integer = 0 To 9
                    atomcode(i, j) = (i * 10000 + j * 1000 + 99)
                Next j
            Next i
    
        End Sub 
    
    End Module