RetroArch/runahead/mem_util.c

76 lines
1.3 KiB
C
Raw Normal View History

2018-03-28 19:22:07 +00:00
#include "mem_util.h"
void *malloc_zero(size_t size)
{
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)
{
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)
{
void *result = malloc(size);
2018-03-28 19:22:07 +00:00
memcpy(result, src, size);
return result;
}
char *strcpy_alloc(const char *sourceStr)
{
size_t len = 0;
char *result = NULL;
if (sourceStr)
2018-03-28 19:22:07 +00:00
len = strlen(sourceStr);
2018-03-28 19:22:07 +00:00
if (len == 0)
return NULL;
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)
{
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;
char *destStr = *destStr_p;
2018-03-28 19:22:07 +00:00
if (!destStr)
2018-03-28 19:22:07 +00:00
{
destStr = strcpy_alloc_force(appendStr);
2018-03-28 19:22:07 +00:00
*destStr_p = destStr;
return;
}
if (!appendStr)
2018-03-28 19:22:07 +00:00
return;
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);
}