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

我在服务器程序中有奇怪的行为.在简单的例子中它工作正常(我在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,为客户端构造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

没有创建第二个套接字,实际上,没有连接调用:: create,但是你可以看到连接有地址.我有想法,某处某事写在函数connection :: create(或类似的东西)的地址上.能帮忙吗,我怎么能抓住这个?

最佳答案 在ubuntu上,我喜欢和valgrind一起跑(
http://valgrind.org/).

sudo apt-get install valgrind
valgrind ./mypgrogram

它没有报告所有问题,但是当它发生时,它将报告性质和来源.

还建议:

valgrind --db-attach=yes ./myprogram

这允许您在检测到违规/未初始化的内存引用时进行调试(回溯,检查)并继续执行程序.

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

06002

如果用std :: unordered_map替换tr1 / unordered_map应该非常简单

例如.快速破解

#include <unordered_map>

namespace std { namespace tr1 {

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

当然这不是一个好习惯,你可能只想在std :: unordered_map和std :: tr1 :: unordered_map之间输入typedef,但是为了快速检查……

点赞