如何捕获 C++ 代码中奇怪的未定义行为?

How to catch strange undefined behaviour in C++ code?

我在服务器程序中有奇怪的行为。在简单的示例中,它工作正常(我在 pion 和 asio 中到处插入跟踪)。

#include <pion/http/server.hpp>
#include <pion/http/response_writer.hpp>
#include <pion/http/response_reader.hpp>
#include <pion/http/request_writer.hpp>
#include <pion/logger.hpp>
#include <pion/scheduler.hpp>

int main()
{
   pion::single_service_scheduler shed;
   shed.set_num_threads(1);
   boost::shared_ptr<pion::http::server> server
   (new pion::http::server(shed, 5000));
   server->add_resource("/", handlerFunction);
   server->start();
   sleep(5);
}

输出是这样的。为acceptor构造socket,为client构造socket,tcp连接建立,一切正常。

basic io object constructor
after service construct
basic io object constructor
after service construct
basic io object constructor
Address of socket is: 0x9855fa4 value: -1
after service construct
1422519945 INFO pion.http.server Added request handler for HTTP resource: 
1422519945 INFO pion.http.server Starting server on port 5000
before connection create
before connection constructor called
basic io object constructor
basic_stream_socket::construct
Address of socket is: 0x9857514 value: -1
after impl.construct
after service construct
basic io object constructor
after service construct
basic io object constructor
after service construct
ssl socket constructed
connection constructor, is_ssl: 0
after connection create: 0x98574f8
before accept
after accept

在具有相同代码的更复杂的程序中,但是使用 oracle 和许多其他库输出是这样的。

basic io object constructor
after service construct
basic io object constructor
after service construct
basic io object constructor
Address of socket is: 0xbfe47a64 value: -1
after service construct
1422525476 INFO pion.http.server Added request handler for HTTP resource: 
before connection create
basic io object constructor
after service construct
basic io object constructor
after service construct
after connection create: 0x8fe8b88
before accept
in connection::async_accept
after accept

没有创建第二个套接字,实际上,没有调用 connection::create,但是连接有地址,如您所见。我有想法,某处写在函数 connection::create (或类似的东西)的地址上。你能帮忙吗,我怎样才能抓住这个?

在 ubuntu,我喜欢 运行 和 valgrind (http://valgrind.org/)。

sudo apt-get install valgrind
valgrind ./mypgrogram

它不会报告所有问题,但是当它报告时,它会报告性质和来源。

同时推荐:

valgrind --db-attach=yes ./myprogram

这允许您调试(回溯、检查)并在检测到 violation/uninitialized 内存引用时继续程序。

On some older Ubunti I had to use sudo to make valgrind be able to attach gdb:

sudo -E valgrind --db-attach=yes ./myprogram

如果 tr1/unordered_map 替换为 std::unordered_map

应该很简单

例如快速破解

#include <unordered_map>

namespace std { namespace tr1 {

    using std::unordered_map;
    using std::hash;
    // etc...
} }
    

当然这不是好的做法,您可能只想在 std::unordered_mapstd::tr1::unordered_map 之间输入定义,但为了快速检查...