Skip to content

Commit

Permalink
add NCI_Strdup
Browse files Browse the repository at this point in the history
  • Loading branch information
wkliao committed Nov 26, 2024
1 parent f64973f commit 899386c
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/drivers/common/mem_alloc.c
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,32 @@ void *NCI_Malloc_fn(size_t size,
}


/*----< NCI_Strdup() >-------------------------------------------------------*/
/* This subroutine is esstentially the same as calling strdup().
*/
void *NCI_Strdup_fn(const char *src,
const int lineno,
const char *func,
const char *filename)
{
if (src == NULL) return NULL;

size_t len = strlen(src);
void *buf = malloc(len + 1);
#ifdef PNETCDF_DEBUG
if (len >= 0 && buf == NULL)
fprintf(stderr, "malloc(%zd) failed in file %s func %s line %d\n",
len, filename, func, lineno);
#endif
if (len > 0) memcpy(buf, src, len);
((char*)buf)[len] = '\0';
#ifdef PNC_MALLOC_TRACE
ncmpii_add_mem_entry(buf, len, lineno, func, filename);
#endif
return buf;
}


/*----< NCI_Calloc_fn() >-----------------------------------------------------*/
/* This subroutine is esstentially the same as calling calloc().
* According to calloc man page, If nelem is 0, then calloc() returns either
Expand Down
6 changes: 6 additions & 0 deletions src/drivers/include/common.h
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ extern void *
NCI_Malloc_fn(size_t size, const int lineno, const char *func,
const char *filename);

extern void *
NCI_Strdup_fn(const char *src, const int lineno, const char *func,
const char *filename);

extern void *
NCI_Calloc_fn(size_t nelem, size_t elsize, const int lineno, const char *func,
const char *filename);
Expand All @@ -71,11 +75,13 @@ NCI_Free_fn(void *ptr, const int lineno, const char *func,

#if defined(PNETCDF_DEBUG) || defined(PNC_MALLOC_TRACE)
#define NCI_Malloc(a) NCI_Malloc_fn(a,__LINE__,__func__,__FILE__)
#define NCI_Strdup(a) NCI_Strdup_fn(a,__LINE__,__func__,__FILE__)
#define NCI_Calloc(a,b) NCI_Calloc_fn(a,b,__LINE__,__func__,__FILE__)
#define NCI_Realloc(a,b) NCI_Realloc_fn(a,b,__LINE__,__func__,__FILE__)
#define NCI_Free(a) NCI_Free_fn(a,__LINE__,__func__,__FILE__)
#else
#define NCI_Malloc(a) malloc(a)
#define NCI_Strdup(a) strdup(a)
#define NCI_Calloc(a,b) calloc(a,b)
#define NCI_Realloc(a,b) realloc(a,b)
#define NCI_Free(a) free(a)
Expand Down

0 comments on commit 899386c

Please sign in to comment.