我是Valgrind的新手(我的CC++已经生疏了),我得到了一个错误。
40 bytes in 1 blocks are definitely lost in loss record 35 of 111
==26930== at 0x4C275C2: operator new(unsigned long) (vg_replace_malloc.c:261)
==26930== by 0x5EFAFDB: cassie_init_with_timeout (cassie.cc:49)
==26930== by 0x46E647: ngx_cassandra_upstream_get_peer (ngx_cassandra_upstream.c:274)
==26930== by 0x41E00B: ngx_event_connect_peer (ngx_event_connect.c:25)
我猜测是char *last_error_string给我带来了麻烦, 但我如何追踪这个问题?
这是我的源码。
Cassie对象的创建
cassie_t cassie;
char *error = NULL;
cassie = new Cassie(host,port,error,CASSIE_ERROR_NONE); /* this is line 49 in the above valgrind trace */
cassie->cassandra = cassandra;
cassie_t是一个Object的结构体
typedef struct Cassie *cassie_t;
我之所以有这个结构是因为我包装了一个C++库,以便从C语言中调用它。
下面是我们的对象cassie_private.h。
#include <string>
#include "libcassandra/cassandra.h"
#include "libcassie/cassie.h"
#ifdef __cplusplus
namespace libcassie {
using namespace std;
using namespace boost;
class Cassie
{
// TODO do we need the host and the port??
public:
const char* host;
int port;
cassie_error_code_t last_error_code;
char* last_error_string; /* I am guessing my memory problem is here */
tr1::shared_ptr<libcassandra::Cassandra> cassandra;
Cassie();
Cassie(const char *&host, int &port,char* &in_error_str, cassie_error_code_t error);
~Cassie();
};
#else
typedef
struct Cassie
Cassie; /* this is for in C */
#endif
}
#endif
这里是cassie_private.cc。
#include "cassie_private.h"
namespace libcassie {
using namespace std;
using namespace libcassandra;
Cassie::Cassie() :
host(),
port(0),
last_error_code(),
last_error_string(NULL),
cassandra()
{}
Cassie::Cassie(const char * &in_host, int &in_port, char* &in_error_str, cassie_error_code_t error) :
host(in_host),
port(in_port),
last_error_code(error),
last_error_string(in_error_str),
cassandra()
{}
Cassie::~Cassie() {
if(last_error_string) delete last_error_string;
}
}
这是在使用结束时为了删除对象而被调用的。
void cassie_free(cassie_t cassie) {
if(!cassie) return;
cassie->~Cassie();
if(cassie) delete cassie;
}
我如何追踪这个内存泄漏?
Valgrind消息意味着你已经分配了一些内存(在cassie.cc的第49行),但是你在没有调用指针的情况下丢失了overwriting指针。delete
上。
你应该跟踪该指针值的去向(无论是在调试器中还是通过检查),以便发现它在哪里丢失。 你可以考虑在指针上设置一个调试器观察点;这将在指针被覆盖的情况下发现问题。 如果你要在调试器中这样做,确保你在编译时没有启用任何优化。