techvice
techvice

Reputation: 1301

Null dereferencing within VB.NET

I'm in the process of reviewing many of our applications. One application came back with quite a few null deference issues. It is worth mentioning is that I am quite unfamiliar with VB.NET so bear with any issues I may relay with my code.

Public Sub SomeMethod()
    Try
        PerformLog("Entering SomeMethod")
        Dim intTemp As Short

        Erase gstrFieldWhatever //Defined earlier: Public gstrFieldWhatever() As String

        ...

        intTemp = intTemp + 1
        ReDim Preserve gstrFieldWhatever(intTemp)
        gstrFieldWhatever(intTemp) = "Z*L-"

The analyzer, Fortify in this case, is reporting that Erase gstrFieldWhatever will cause a potential null exception when we try to call it later at gstrFieldWhatever(intTemp) = "Z*L-". However, we using ReDim Preserve gstrFieldWhatever(intTemp) should create a new array. If this is the case, why would the analyzer indicate a potential null dereference issue?

Upvotes: 1

Views: 392

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 415725

The gstrFieldWhatever is a public field. There's a risk if this object is used in multi-threaded code, because the field could be accessed between when it is freed and when it is ReDimmed.

In most cases, the use of ReDim Preserve indicates a place where you really want a collection like List(Of String), however, I understand if that change might cascade into other areas of the code.

Upvotes: 2

Related Questions