Safeguard
Application Security•

CWE-1046 Building Strings by Concatenation in Loops

Appending to an immutable string in a loop creates a new object every pass. CWE-1046 shows the cost, how an attacker can abuse it, and the buffer fix.

Safeguard Security Team
2 min read

CWE-1046 covers a common performance habit: the product creates an immutable text string using string concatenation operations. MITRE lists it as a Base weakness in any language.

How it happens

When a loop builds a string with +=, each pass creates a new string object, because the old one cannot be changed. MITRE points out this is inefficient compared with text buffer data elements.

// Slower: a new String object on every iteration
String out = "";
for (String part : parts) {
    out += part;
}
// Better: one growing buffer
StringBuilder out = new StringBuilder();
for (String part : parts) {
    out.append(part);
}
String result = out.toString();

The recorded consequence is reduced performance. If the relevant code is reachable by an attacker, they may be able to influence it to create a performance problem, for example by supplying input that makes the loop run many times. No CVEs are observed.

How to find it

MITRE lists no detection methods. Linters and static analysis often flag concatenation inside loops. Profiling shows allocation hot spots.

How to fix it

MITRE lists no formal mitigations. Reasonable steps:

  1. Use a string builder, buffer or join function when assembling text in a loop.
  2. Bound the number of iterations that user input can cause.
  3. Profile with large inputs before release.

Note that many modern runtimes optimize simple cases, so measure before rewriting working code. The risk is highest where input size is attacker controlled.

Quick check

Why is += in a loop slow for immutable strings?

Each append creates a new string object instead of changing the existing one.

Sources

Never miss an update

Weekly insights on software supply chain security, delivered to your inbox.

Self-healing security runs on Safeguard.

Your first fix PR is minutes away.

No sales call required, even your agent can complete the purchase over MCP.