Примеры ошибок, обнаруженных с помощью диагностики V3080


V3080. Possible null dereference.


Accord.Net

V3080 Possible null dereference. Consider inspecting 'fmt'. Accord.Statistics MultivariateMixture'1.cs 697


public override string ToString(string format,
                                IFormatProvider formatProvider)
{
  ....
  var fmt = components[i] as IFormattable;
  if (fmt != null)
    sb.AppendFormat(fmt.ToString(format, formatProvider));
  else
    sb.AppendFormat(fmt.ToString());
  ....
}

Old NASA World Wind (C#)

V3080 Possible null dereference. Consider inspecting 'm_gpsIcon'. GpsTrackerPlugin.SourceSetup.cs 68


public GpsSetup(....)
{
  ....
  if (m_gpsIcon!=null)
  {
    ....
    labelTitle.Text = "Set options for " +
                      m_gpsIcon.m_RenderInfo.sDescription;
  }
  else
  if (m_gpsTrackLine != null)
  {
    ....
    labelTitle.Text = "Set options for " +
                      m_gpsIcon.m_RenderInfo.sDescription; // <=
  }
  ....
}

Unity3D

V3080 Possible null dereference. Consider inspecting 't.staticFieldBytes'. MemoryProfiller CrawledDataUnpacker.cs 20


public static CrawledMemorySnapshot Unpack(....)
{
  ....
  var result = new CrawledMemorySnapshot
  {
    ....
    staticFields = packedSnapshot.typeDescriptions
      .Where(t =>
        t.staticFieldBytes != null & // <=
        t.staticFieldBytes.Length > 0)
      .Select(t => UnpackStaticFields(t))
      .ToArray(),
    ....
  };
  ....
}

PowerShell

V3080 Possible null dereference. Consider inspecting 'ItemSelectionCondition'. System.Management.Automation displayDescriptionData_List.cs 352


internal bool SafeForExport()
{
  return DisplayEntry.SafeForExport() &&
         ItemSelectionCondition == null
      || ItemSelectionCondition.SafeForExport();
}

Similar errors can be found in some other places:

  • V3080 Possible null dereference. Consider inspecting 'EntrySelectedBy'. System.Management.Automation displayDescriptionData_Wide.cs 247

PowerShell

V3080 Possible null dereference. Consider inspecting 'providerName'. System.Management.Automation SessionStateProviderAPIs.cs 1004


internal Collection<ProviderInfo> GetProvider(
  PSSnapinQualifiedName providerName)
{
  ....
  if (providerName == null)
  {
    ProviderNotFoundException e =
      new ProviderNotFoundException(
          providerName.ToString(),
          SessionStateCategory.CmdletProvider,
          "ProviderNotFound",
          SessionStateStrings.ProviderNotFound);

    throw e;
  }
  ....
}

Similar errors can be found in some other places:

  • V3080 Possible null dereference. Consider inspecting 'job'. System.Management.Automation PowerShellETWTracer.cs 1088

Umbraco

V3080 Possible null dereference. Consider inspecting 'context.Request'. StateHelper.cs 369


public static bool HasCookies
{
  get
  {
    var context = HttpContext;
    return context != null && context.Request != null &
           context.Request.Cookies != null &&
           context.Response != null &&
           context.Response.Cookies != null;
  }
}

Media Portal 2

V3080 Possible null dereference. Consider inspecting 'BannerPath'. TvdbBannerWithThumb.cs 91


public bool LoadThumb(bool replaceOld)
{
  ....
  if (ThumbPath == null &&
     (BannerPath != null || BannerPath.Equals(""))) // <=
  {
    ThumbPath = String.Concat("_cache/", BannerPath);
  }
  ....
}

.NET Core Libraries (CoreFX)

V3080 Possible null dereference. Consider inspecting 'tabClasses'. PropertyTabAttribute.cs 225


private void InitializeArrays(string[] tabClassNames,
  Type[] tabClasses, PropertyTabScope[] tabScopes)
{
  if (tabClasses != null)
  {
    if (tabScopes != null &&
        tabClasses.Length != tabScopes.Length)
    {
      ....
    }
    _tabClasses = (Type[])tabClasses.Clone();
  }
  else if (tabClassNames != null)
  {
    if (tabScopes != null &&
        tabClasses.Length != tabScopes.Length) // <=
    {
      ....
    }
    _tabClassNames = (string[])tabClassNames.Clone();
    _tabClasses = null;
  }

  ....
}

Used 'tabClasses' instead of 'tabClassNames'.

Similar errors can be found in some other places:

  • V3080 Possible null dereference. Consider inspecting 'BaseSimpleType'. SimpleType.cs 368

PascalABC.NET

V3080 Possible null dereference. Consider inspecting 'tc'. CodeCompletion CodeCompletionPCUReader.cs 736


private TypeScope GetTemplateInstance()
{
  TypeScope tc = null;//GetTemplateClassReference();
  int params_count = br.ReadInt32();
  for (int i = 0; i < params_count; i++)
  {
    tc.AddGenericInstanciation(GetTypeReference());  // <=
  }
  return tc;
}

Similar errors can be found in some other places:

  • V3080 Possible null dereference. Consider inspecting 'bfc'. TreeConverter syntax_tree_visitor.cs 7334
  • V3080 Possible null dereference. Consider inspecting 'bfc'. TreeConverter syntax_tree_visitor.cs 7336
  • V3080 Possible null dereference. Consider inspecting 'bfc'. TreeConverter syntax_tree_visitor.cs 7338
  • And 5 additional diagnostic messages.

Unity C# reference source code

V3080 CWE-476 Possible null dereference. Consider inspecting 'm_Parent'. EditorWindow.cs 449


public void ShowPopup()
{
  if (m_Parent == null)
  {
    ....
    Rect r = m_Parent.borderSize.Add(....);
    ....
  }
}

Unity C# reference source code

V3080 CWE-476 Possible null dereference. Consider inspecting 'm_Parent'. EditorWindow.cs 470


internal void ShowWithMode(ShowMode mode)
{
  if (m_Parent == null)
  {
    ....
    Rect r = m_Parent.borderSize.Add(....);
    ....
}

Unity C# reference source code

V3080 CWE-476 Possible null dereference. Consider inspecting 'objects'. TypeSelectionList.cs 48


public TypeSelection(string typeName, Object[] objects)
{
  System.Diagnostics.Debug.Assert(objects != null ||
                                  objects.Length >= 1);
  ....
}

Unity C# reference source code

V3080 CWE-476 Possible null dereference. Consider inspecting 'm_RowRects'. TreeViewControlGUI.cs 272


public override void GetFirstAndLastRowVisible(....)
{
  ....
  if (rowCount != m_RowRects.Count)
  {
    m_RowRects = null;
    throw new InvalidOperationException(string.Format("....",
              rowCount, m_RowRects.Count));
  }
  ....
}

Unity C# reference source code

V3080 CWE-476 Possible null dereference. Consider inspecting 'additionalOptions'. MonoCrossCompile.cs 279


static void CrossCompileAOT(....)
{
  ....
  if (additionalOptions != null & additionalOptions.Trim().Length
      > 0)
    arguments += additionalOptions.Trim() + ",";
  ....
}

Infer.NET

V3080 Possible null dereference. Consider inspecting 'value'. Compiler WriteHelpers.cs 78


public static void WriteAttribute(TextWriter writer,
                                  string name,
                                  object defaultValue,
                                  object value,
                                  Func<object, string> converter = null)
{
  if (defaultValue == null && value == null || value.Equals(defaultValue))
  {
    return;
  }

  string stringValue = converter == null ? value.ToString() : converter(value);
  writer.Write($"{name}=\"{stringValue}\" ");
}

Infer.NET

V3080 Possible null dereference. Consider inspecting 'traitFeatureWeightDistribution'. Recommender FeatureParameterDistribution.cs 65


public FeatureParameterDistribution(
         GaussianMatrix traitFeatureWeightDistribution,
         GaussianArray biasFeatureWeightDistribution)
{
  Debug.Assert(
    (traitFeatureWeightDistribution == null &&
     biasFeatureWeightDistribution == null)
     ||
     traitFeatureWeightDistribution.All(
       w =>    w != null
            && w.Count == biasFeatureWeightDistribution.Count),
    "The provided distributions should be valid
     and consistent in the number of features.");
  ....
}

.NET Core Libraries (CoreFX)

V3080 Possible null dereference. Consider inspecting 'attr'. DbConnectionStringBuilder.cs 534


private PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
  ....
  foreach (Attribute attribute in attributes)
  {
    Attribute attr = property.Attributes[attribute.GetType()];
    if (   (attr == null && !attribute.IsDefaultAttribute())
        || !attr.Match(attribute))
      ....
  }
  ....
}

.NET Core Libraries (CoreFX)

V3080 Possible null dereference. Consider inspecting 'hasher'. PKCS1MaskGenerationMethod.cs 37


public override byte[] GenerateMask(byte[] rgbSeed, int cbReturn)
{
  using (HashAlgorithm hasher
    = (HashAlgorithm)CryptoConfig.CreateFromName(_hashNameValue)) // <=
  {
    ....
    for (....)
    {
      ....
      hasher.TransformBlock(rgbSeed, 0, rgbSeed.Length, rgbSeed, 0); // <=
      ....
    }
    return rgbT;
  }
}

public static object CreateFromName(string name)
{
  return CreateFromName(name, null);
}

public static object CreateFromName(string name, params object[] args)
{
  ....
  if (retvalType == null)
  {
    return null;
  }
  ....
  if (cons == null)
  {
    return null;
  }
  ....

  if (candidates.Count == 0)
  {
    return null;
  }
  ....
  if (rci == null || typeof(Delegate).IsAssignableFrom(rci.DeclaringType))
  {
    return null;
  }
  ....
  return retval;
}

Similar errors can be found in some other places:

  • V3080 Possible null dereference. Consider inspecting 'item'. SignatureDescription.cs 31
  • V3080 Possible null dereference. Consider inspecting 'item'. SignatureDescription.cs 38

Roslyn Analyzers

V3080 Possible null dereference of method return value. Consider inspecting: GetCandidateReferencedSymbols(...). SyntaxNodeHelper.cs 78


public static IEnumerable<IMethodSymbol> GetCandidateCalleeMethodSymbols(
  SyntaxNode node, SemanticModel semanticModel)
{
  foreach (ISymbol symbol in GetCandidateReferencedSymbols(
                              node, semanticModel))
  {
     if (symbol != null && symbol.Kind == SymbolKind.Method)
     {
        yield return (IMethodSymbol)symbol;
     }
  }
}

Roslyn Analyzers

V3080 Possible null dereference. Consider inspecting 'oldIdName'. CodeFixProvider.cs 1476


private async Task<Document> IdDeclTypeAsync(....)
{
  ....
  ExpressionSyntax oldIdName = null;
  foreach (MemberDeclarationSyntax memberSyntax in members)
  {
     var fieldDeclaration = memberSyntax as FieldDeclarationSyntax;
     if (fieldDeclaration == null)
       continue;
     if (fieldDeclaration.Declaration.Type is IdentifierNameSyntax fieldType
         && fieldType.Identifier.Text == "DiagnosticDescriptor")
     {
       ....
       for (int i = 0; i < ruleArgumentList.Arguments.Count; i++)
       {
         ArgumentSyntax currentArg = ruleArgumentList.Arguments[i];
         string currentArgName = currentArg.NameColon.Name.Identifier.Text;
         if (currentArgName == "id")
         {
           oldIdName = currentArg.Expression;
           break;
         }
       }
       continue;
    }
    ....
  }
  var newRule = rule.ReplaceNode(oldIdName.Ancestors()   // <=
                    .OfType<ArgumentSyntax>()
                    .First(), newArg);
  ....
}

Roslyn Analyzers

V3080 Possible null dereference. Consider inspecting 'methodDeclaration'. DiagnosticAnalyzer.cs 506


private bool CheckIfStatementAnalysis(...
  IMethodSymbol analysisMethodSymbol)
{
  var methodDeclaration = AnalysisGetStatements(analysisMethodSymbol)
                           as MethodDeclarationSyntax;
  var body = methodDeclaration.Body as BlockSyntax;
  if (body == null)
  { return false; }
  ....
}

private MethodDeclarationSyntax AnalysisGetStatements(
   IMethodSymbol
   analysisMethodSymbol)
{
  MethodDeclarationSyntax result = null;
  if (analysisMethodSymbol == null)
  {
     return result;
  }
  var methodDeclaration = analysisMethodSymbol
                            .DeclaringSyntaxReferences[0]
                            .GetSyntax() as MethodDeclarationSyntax;
  if (methodDeclaration == null)
  {
     return result;
  }
  return methodDeclaration;
}

Orchard CMS

V3080 Possible null dereference. Consider inspecting 'itemTag'. CoreShapes.cs 92


public async Task<IHtmlContent> List(.... string ItemTag....)
{
  ....
  string itemTagName = null;
  if (ItemTag != "-")
  {
    itemTagName = string.IsNullOrEmpty(ItemTag) ? "li" : ItemTag;
  }
  var index = 0;
  foreach (var item in items)
  {
    var itemTag = String.IsNullOrEmpty(itemTagName) ? null : ....;
    ....
    itemTag.InnerHtml.AppendHtml(itemContent);
    listTag.InnerHtml.AppendHtml(itemTag);
    ++index;
  }
  return listTag;
}

Orchard CMS

V3080 Possible null dereference of method return value. Consider inspecting: CreateScope(). SetupService.cs 136


public async Task<string> SetupInternalAsync(SetupContext context)
{
  ....
  using (var shellContext = await ....)
  {
    await shellContext.CreateScope().UsingAsync(....);
  }
  ....
}

public ShellScope CreateScope()
{
  if (_placeHolder)
  {
    return null;
  }
  var scope = new ShellScope(this);
  // A new scope can be only used on a non released shell.
  if (!released)
  {
    return scope;
  }
  scope.Dispose();
  return null;
}

Similar errors can be found in some other places:

  • V3080 Possible null dereference of method return value. Consider inspecting: CreateScope(). SetupService.cs 192

Orchard CMS

V3080 Possible null dereference. Consider inspecting 'request'. GraphQLMiddleware.cs 148


private async Task ExecuteAsync(HttpContext context....)
{
  ....
  GraphQLRequest request = null;
  ....
  if (HttpMethods.IsPost(context.Request.Method))
  {
    ....
  }
  else if (HttpMethods.IsGet(context.Request.Method))
  {
    ....
    request = new GraphQLRequest();
    ....
  }
  var queryToExecute = request.Query;
  ....
}

public static TElement Get<TElement>(this ContentElement contentElement....)
        where TElement : ContentElement
{
    return (TElement)contentElement.Get(typeof(TElement), name);
}

public static ContentElement Get(this ContentElement contentElement....)
{
  ....
  var elementData = contentElement.Data[name] as JObject;
  if (elementData == null)
  {
    return null;
  }
  ....
}

Orchard CMS

V3080 Possible null dereference of method return value. Consider inspecting: Get<ContentPart>(...). ContentPartHandlerCoordinator.cs 190


public override async Task LoadingAsync(LoadContentContext context)
{
  ....
  context.ContentItem.Get<ContentPart>(typePartDefinition.Name)
                     .Weld(fieldName, fieldActivator.CreateInstance());
  ....
}

public static async Task<IEnumerable> QueryAsync(....)
{
  ....
  var query = await queryManager.GetQueryAsync(queryName);
  if (query == null)
  {
    return null;
  }
  ....
}

Orchard CMS

V3080 Possible null dereference. Consider inspecting 'results'. ContentQueryOrchardRazorHelperExtensions.cs 19


public static async Task<IEnumerable<ContentItem>> ContentQueryAsync(....)
{
  var results = await orchardHelper.QueryAsync(queryName, parameters);
  ....
  foreach (var result in results)
  {
    ....
  }
  ....
}


Найденные ошибки

Проверено проектов
363
Собрано ошибок
13 495

А ты совершаешь ошибки в коде?

Проверь с помощью
PVS-Studio

Статический анализ
кода для C, C++, C#
и Java

goto PVS-Studio;