static or dynamic code analysis for undefined behavior in sprintf

Hi,

Today I came across the exact same bug as described in this SO post: https://stackoverflow.com/questions/1283354/is-sprintfbuffer-s-buffer-safe
sprintf(buffer, “%s”, buffer) has undefined behavior. And as it turns out, this code fails on the new platform where I’m porting this legacy code, while it was working on the old platform.

Unless I missed something, It looks like there is no clang-tidy check, nor anything implemented for UB sanitizer.
Is there any reason for this? Did someone try to work on this in the past?

If not, but if you think this could be of interest, I can try to write a patch for this.
What do you think would be the best place to have such a check?
I feel like UB sanitizer would catch more errors than static analyzer, which will have a hard time catching more complex cases e.g. when two variables point to the same address.
Still, it might be useful to have basic checks for clang-tidy to catch obvious cases.

Kind regards,
Arnaud

Interesting. I haven't heard of any efforts to detect these bugs.

Between a runtime sanitizer and a clang-tidy check, a clang static analyzer check could offer a nice middle ground solution as it can *sometimes* detect two variables pointing to the same address. I.e., it can naturally handle cases like

char *x = buffer;
char *y = buffer;
sprintf(x, "%s", y);

or even

if (x == y)
sprintf(x, "%s", y);

but it won't warn if it doesn't see in the surrounding code that these pointers were assigned the same buffer. It has to simulate the instructions that suggest that while analyzing small portions of the code at a time.