Skip to content

nall/string/replace.hpp breaks if the original string starts with the pattern to replace #1

@Screwtapello

Description

@Screwtapello

Reported by byuu on Twitter:

I can't believe this bug lurked until 2020. nall/string/replace.hpp, when replacing a longer string with a shorter one, has an erroneous if(offset) check that needs to be removed. If a string starts with the pattern to remove, it won't perform a needed move on the second loop.

nall/string/replace.hpp

Lines 47 to 58 in 3fb2114

for(int n = 0, remaining = matches, quoted = 0; n <= size - (int)from.size();) {
if(Quoted) { if(p[n] == '\"') { quoted ^= 1; n++; continue; } if(quoted) { n++; continue; } }
if(_compare<Insensitive>(p + n, size - n, from.data(), from.size())) { n++; continue; }
if(offset) memory::move(p + offset, p + base, n - base);
memory::copy(p + offset + (n - base), to.data(), to.size());
offset += (n - base) + to.size();
n += from.size();
base = n;
if(!--remaining) break;
}

(the offending if(offset) is on line 51)

So for instance, string("\r\nTest!\r\n").replace("\r", "") was generating "\r\nTest\n" rather than "\nTest!\n", which was dangerously wrong. This basically affects everything I've ever made. bsnes, higan, bass, everything ... needs to be updated, this is quite critical.

[...]

Maybe it was meant to just prevent an unnecessary move directly on top of itself when a string didn't start with the pattern to replace. Something like if(base) would've been the correct code in that case.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workinggood first issueGood for newcomers

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions