1

To my understanding this code snippet has a problem, since std::string will be removed after to_string and port should have an incorrect value.

#include <iostream>
#include <stdio.h>

int main() {
        int a = 123;
        const char* port = std::to_string(a).c_str();
        printf("val = %s", port);

        return 0;
}

However, program works just fine and prints "123" (with g++ compiler). Valgrind does not spot a problem as well.

Is there any way to demonstrate (maybe some tool or compiler option) that code above indeed has a problem?

lstipakov
  • 3,138
  • 5
  • 31
  • 46

1 Answers1

2

No, you cannot "detect" undefined behaviour, in general. Electric Fence may help.

You should catch these kinds of problems during peer review.

It is also possible to almost eradicate the risk of creating them, by avoiding const char* entirely.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055