2018-03-28 19:22:07 +00:00
|
|
|
#include "mem_util.h"
|
|
|
|
|
|
|
|
void *malloc_zero(size_t size)
|
|
|
|
{
|
2018-03-29 13:13:33 +00:00
|
|
|
void *ptr = malloc(size);
|
2018-03-28 19:22:07 +00:00
|
|
|
memset(ptr, 0, size);
|
|
|
|
return ptr;
|
|
|
|
}
|
|
|
|
|
|
|
|
void free_str(char **str_p)
|
|
|
|
{
|
|
|
|
free_ptr((void**)str_p);
|
|
|
|
}
|
|
|
|
|
|
|
|
void free_ptr(void **data_p)
|
|
|
|
{
|
2018-03-29 13:13:33 +00:00
|
|
|
if (!data_p || !*data_p)
|
2018-03-28 19:22:07 +00:00
|
|
|
return;
|
|
|
|
free(*data_p);
|
|
|
|
*data_p = NULL;
|
|
|
|
}
|
|
|
|
|
|
|
|
void *memcpy_alloc(const void *src, size_t size)
|
|
|
|
{
|
2018-03-29 13:13:33 +00:00
|
|
|
void *result = malloc(size);
|
2018-03-28 19:22:07 +00:00
|
|
|
memcpy(result, src, size);
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
char *strcpy_alloc(const char *sourceStr)
|
|
|
|
{
|
2018-03-29 13:13:33 +00:00
|
|
|
size_t len = 0;
|
|
|
|
char *result = NULL;
|
|
|
|
|
|
|
|
if (sourceStr)
|
2018-03-28 19:22:07 +00:00
|
|
|
len = strlen(sourceStr);
|
2018-03-29 13:13:33 +00:00
|
|
|
|
2018-03-28 19:22:07 +00:00
|
|
|
if (len == 0)
|
|
|
|
return NULL;
|
2018-03-29 13:13:33 +00:00
|
|
|
|
2018-03-28 19:22:07 +00:00
|
|
|
result = (char*)malloc(len + 1);
|
|
|
|
strcpy(result, sourceStr);
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
char *strcpy_alloc_force(const char *sourceStr)
|
|
|
|
{
|
2018-03-29 13:13:33 +00:00
|
|
|
char *result = strcpy_alloc(sourceStr);
|
|
|
|
if (!result)
|
2018-03-28 19:22:07 +00:00
|
|
|
result = (char*)malloc_zero(1);
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
void strcat_alloc(char ** destStr_p, const char *appendStr)
|
|
|
|
{
|
|
|
|
size_t len1, len2, newLen;
|
2018-03-29 13:13:33 +00:00
|
|
|
char *destStr = *destStr_p;
|
2018-03-28 19:22:07 +00:00
|
|
|
|
2018-03-29 13:13:33 +00:00
|
|
|
if (!destStr)
|
2018-03-28 19:22:07 +00:00
|
|
|
{
|
2018-03-29 13:13:33 +00:00
|
|
|
destStr = strcpy_alloc_force(appendStr);
|
2018-03-28 19:22:07 +00:00
|
|
|
*destStr_p = destStr;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2018-03-29 13:13:33 +00:00
|
|
|
if (!appendStr)
|
2018-03-28 19:22:07 +00:00
|
|
|
return;
|
|
|
|
|
2018-03-29 13:13:33 +00:00
|
|
|
len1 = strlen(destStr);
|
|
|
|
len2 = strlen(appendStr);
|
|
|
|
newLen = len1 + len2 + 1;
|
|
|
|
destStr = (char*)realloc(destStr, newLen);
|
2018-03-28 19:22:07 +00:00
|
|
|
*destStr_p = destStr;
|
|
|
|
strcpy(destStr + len1, appendStr);
|
|
|
|
}
|