Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Published by Scroll Versions from space CSHARP and version Publish
Panel
borderColorgray
borderStyledashed

Name: Unused format argument

Description:

Excerpt
Supplying more arguments than are required for a format string may indicate an error in the format string.

ID: cs/format-argument-unused

Kind: path-problem

Severity: warning

Precision: high

Dont print
Code Block
languageql
titleQuery: FormatUnusedArgument.ql
collapsetrue
/**
 * @name Unused format argument
 * @description Supplying more arguments than are required for a format string may indicate an error in the format string.
 * @kind path-problem
 * @problem.severity warning
 * @precision high
 * @id cs/format-argument-unused
 * @tags reliability
 *       maintainability
 */

import csharp
import semmle.code.csharp.frameworks.Format
import FormatFlow

from FormatCall format, int unused, ValidFormatString src, PathNode source, PathNode sink
where
  hasFlowPath(src, =source, format.getAFormatSource(, sink) and
  unused = format.getAnUnusedArgument(src) and
  not src.getValue() = ""
select format, source, sink, "The $@ ignores $@.", src, "format string",
  format.getSuppliedExpr(unused),   "this supplied value"

Arguments which are passed to formatting methods (such as String.Format()) but are not used, are either unnecessary or mean that the format string is incorrect. The result is that the argument will be ignored, which may not be the intended behavior.

Recommendation

Change the format string to use the highlighted argument, or remove the unnecessary argument.

Example

Here are three examples where the format string does not use all the arguments.

Print only
     1using System;
     2
     3class Bad
     4{
     5    void M(Exception ex)
     6    {
     7        Console.WriteLine("Error processing file: {0}", ex, ex.HResult);
     8        Console.WriteLine("Error processing file: {1} ({1})", ex, ex.HResult);
     9        Console.WriteLine("Error processing file: %s (%d)", ex, ex.HResult);
    10    }
    11}
Dont print
Code Block
languagecsharp
themeEclipse
linenumberstrue
using System;

class Bad
{
    void M(Exception ex)
    {
        Console.WriteLine("Error processing file: {0}", ex, ex.HResult);
        Console.WriteLine("Error processing file: {1} ({1})", ex, ex.HResult);
        Console.WriteLine("Error processing file: %s (%d)", ex, ex.HResult);
    }
}
  • On line 5, the second argument (ex.HResult) is not logged.
  • On line 6, the first argument (ex) is not logged but the second argument (ex.HResult) is logged twice.
  • On line 4, a C-style format string is used, which is incorrect, and neither argument will be logged.
References
Htmlcomment
hiddentrue
hashconfluence_uploader_hash:115eaf20b56f714a210a711691360fd6cd671b96e200a30bb86a10b7f49342f6d4bc6c5f19a7f6c4