MEMORY add wrappers around all mallocs and frees and trace them

This patch adds a wrapper around all memory allocations and frees.
The idea is to get warned immediately if the application leaks memory.
Additionally the wrapper functions make it easy to add different
memory allocators or memory pools in the future.
This commit is contained in:
Peter Lieven
2012-11-03 01:05:57 +01:00
parent 389f6a8ba5
commit d327ab09c6
11 changed files with 300 additions and 287 deletions

View File

@@ -33,23 +33,50 @@
#include "iscsi-private.h"
#include "slist.h"
inline void* iscsi_malloc(struct iscsi_context *iscsi, size_t size) {
void * ptr = malloc(size);
if (ptr != NULL) iscsi->mallocs++;
return ptr;
}
inline void* iscsi_zmalloc(struct iscsi_context *iscsi, size_t size) {
void * ptr = malloc(size);
if (ptr != NULL) {
memset(ptr,0x00,size);
iscsi->mallocs++;
}
return ptr;
}
inline void iscsi_free(struct iscsi_context *iscsi, void* ptr) {
if (ptr == NULL) return;
free(ptr);
iscsi->frees++;
}
inline char* iscsi_strdup(struct iscsi_context *iscsi, const char* str) {
char *str2 = strdup(str);
if (str2 != NULL) iscsi->mallocs++;
return str2;
}
struct iscsi_context *
iscsi_create_context(const char *initiator_name)
{
struct iscsi_context *iscsi;
if (!initiator_name[0]) {
return NULL;
}
iscsi = malloc(sizeof(struct iscsi_context));
if (iscsi == NULL) {
return NULL;
}
memset(iscsi, 0, sizeof(struct iscsi_context));
strncpy(iscsi->initiator_name,initiator_name,MAX_STRING_SIZE);
if (!iscsi->initiator_name[0]) {
free(iscsi);
return NULL;
}
iscsi->fd = -1;
@@ -226,14 +253,20 @@ iscsi_destroy_context(struct iscsi_context *iscsi)
}
if (iscsi->incoming != NULL) {
iscsi_free_iscsi_in_pdu(iscsi->incoming);
iscsi_free_iscsi_in_pdu(iscsi, iscsi->incoming);
}
if (iscsi->inqueue != NULL) {
iscsi_free_iscsi_inqueue(iscsi->inqueue);
iscsi_free_iscsi_inqueue(iscsi, iscsi->inqueue);
}
iscsi->connect_data = NULL;
if (iscsi->mallocs != iscsi->frees) {
DPRINTF(iscsi,1,"%d memory blocks lost at iscsi_destroy_context() after %d mallocs and %d frees",iscsi->mallocs-iscsi->frees,iscsi->mallocs,iscsi->frees);
} else {
DPRINTF(iscsi,5,"memory is clean at iscsi_destroy_context() after %d mallocs and %d frees",iscsi->mallocs,iscsi->frees);
}
free(iscsi);
return 0;
@@ -391,12 +424,12 @@ iscsi_parse_url(struct iscsi_context *iscsi, const char *url, int full)
if (tmp) *tmp=0;
}
iscsi_url = malloc(sizeof(struct iscsi_url));
iscsi_url = iscsi_zmalloc(iscsi, sizeof(struct iscsi_url));
if (iscsi_url == NULL) {
iscsi_set_error(iscsi, "Out-of-memory: Failed to allocate iscsi_url structure");
return NULL;
}
memset(iscsi_url, 0, sizeof(struct iscsi_url));
iscsi_url->iscsi= iscsi;
strncpy(iscsi_url->portal,portal,MAX_STRING_SIZE);
@@ -428,7 +461,7 @@ iscsi_parse_portal_url(struct iscsi_context *iscsi, const char *url)
void
iscsi_destroy_url(struct iscsi_url *iscsi_url)
{
free(iscsi_url);
iscsi_free(iscsi_url->iscsi, iscsi_url);
}