[AGENT++] Hi, all, why these code lead to memry leak?
cheng wan
wancheng82 at gmail.com
Mon Mar 1 08:27:51 CET 2010
The code below is main for:
1)Get tcp info from /proc/net/tcp.
2)tcp_conn_table_index() is to compute the index of tcpConnEntry.
Indexes: 1: tcpConnLocalAddress
2: tcpConnLocalPort
3: tcpConnRemAddress
4: tcpConnRemPort
3)Before add one row to tcpConnEntry::instance, I use
tcpConnEntry::instance->clear() to clear all the rows
4)get_proc_net_tcp() is excuted by one 2 seconds timer
The memory keeps growning.
Thank you all.
uin32_t tcp_conn_local_address, tcp_conn_local_port, tcp_conn_rem_address,
tcp_conn_rem_port, tcp_conn_state;
void tcp_conn_table_index(struct in_addr local_address,
uint32_t local_port,
struct in_addr rem_address,
uint32_t rem_port,
char *buf) {
char *local_address_ptr = inet_ntoa(local_address); // in_addr to char *
IpAddress ip_address_one(local_address_ptr);
char *rem_address_ptr = inet_ntoa(rem_address); // in_addr to char *
IpAddress ip_address_two(rem_address_ptr);
snprintf(buf, MAXLINE, "%d.%d.%d.%d.%d.%d.%d.%d.%d.%d",
(unsigned char)ip_address_one[0],
(unsigned char)ip_address_one[1],
(unsigned char)ip_address_one[2],
(unsigned char)ip_address_one[3],
local_port,
(unsigned char)ip_address_two[0],
(unsigned char)ip_address_two[1],
(unsigned char)ip_address_two[2],
(unsigned char)ip_address_two[3],
rem_port
);
}
void get_proc_net_tcp()
{
FILE *in = NULL;
in = fopen ("/proc/net/tcp", "r");
char line [MAXLINE];
int32_t num;
static int map_states[] = { 1, 5, 3, 4, 7, 10, 11, 1, 6, 9, 2, 8 };
if(!in) {
XLOG_WARNING("unable to open /proc/net/tcp, %s\n", strerror(errno));
return false;
}
tcpConnEntry::instance->clear();
while (line == fgets(line, sizeof(line), in)) {
sscanf(line, "%d: %x:%x %x:%x %x", &num,
&tcp_conn_local_address,
&tcp_conn_local_port,
&tcp_conn_rem_address,
&tcp_conn_rem_port,
&tcp_conn_state);
struct in_addr local_address, rem_address;
memcpy(&local_address, &tcp_conn_local_address, sizeof(struct in_addr));
memcpy(&rem_address, &tcp_conn_rem_address, sizeof(struct in_addr));
string local_address_str = inet_ntoa(local_address);
string rem_address_str = inet_ntoa(rem_address);
char buf[MAXLINE];
memset(buf, 0, sizeof(buf));
tcp_conn_table_index(local_address, tcp_conn_local_port,
rem_address, tcp_conn_rem_port, buf);
MibTableRow* row = tcpConnEntry::instance->add_row(buf);
if((tcp_conn_state >= 0) && (tcp_conn_state < 12)) {
tcp_conn_state = map_states[tcp_conn_state];
} else {
tcp_conn_state = 1;
}
tcpConnEntry::instance->set_row(row,
tcp_conn_state,
local_address_str.c_str(),
tcp_conn_local_port,
rem_address_str.c_str(),
tcp_conn_rem_port
);
}
fclose(in);
return true;
}
More information about the AGENTPP
mailing list