1

I am getting the wrong std::string size value.

statsd_link* statsd_init(std::string& host, int port) {
    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG,
         "statsd_init print data to %s:%d and length: %ld, %ld\n", 
             host.c_str(), port, strlen(host.c_str()), host.size());
}

And the output is:

2019-06-22 20:55:35.553331 [DEBUG] statsd_init print data to 127.0.0.1:8125 and length: 9, 0
L. F.
  • 19,445
  • 8
  • 48
  • 82
Shravan40
  • 8,922
  • 6
  • 28
  • 48
  • 2
    Smells of UB being involved. How is `host` created and filled with data before it is passed to your function? – Yksisarvinen Jun 22 '19 at 15:42
  • 2
    What does switch_log_printf does? The docs I found here https://docs.freeswitch.org/group__log.html#ga8b2e27a937f0e0fef00d1eae3ddedd14 seems to indicate that it needs more arguments. Have you tried extracting the two sizes in a different line and then feed them to switch_log_printf ? The other possibility is that something else is de-allocating or clearing the string, but then I would expect to see a sporadic issue. – CuriouslyRecurringThoughts Jun 22 '19 at 15:50
  • 3
    `strlen()` and `size()` both return a `size_t`, and `%ld` is the wrong format specifier for that type. There is no standardized specifier for `size_t` in C++, but [there is one in C](https://stackoverflow.com/questions/2524611/). You should be using iostreams in C++ instead – Remy Lebeau Jun 22 '19 at 16:07
  • 2
    @RemyLebeau: `%zu` is in C++11, since it incorporates the C99 standard library. `%lu` (or even `%ld`) will probably work in **practice** on modern systems except for Windows (but don’t do that!). – Davis Herring Jun 22 '19 at 17:56

0 Answers0