Makistos
10/28/2013 - 7:52 AM

Function that can be used to make a duplicate of a string in C. #string-handling #c

Function that can be used to make a duplicate of a string in C. #string-handling #c

#include <stdlib.h>
#include <string.h>

/** Allocates a buffer and copies source buffer to it.
 *
 * @param dst Pointer to pointer to buffer where the copy is returned in.
 * @param src Source buffer to copy.
 *
 * @returns 0 = Operation succeeded, -1 = Memory allocation
 *          failed.
 */

HWT_STATUS StrDup(char **dst, char *src)
{
	size_t len = strlen(src) + 1;

	*dst = malloc(len);
	
	if (*dst == NULL) {
		return -1;
	}
	strncpy(*dst, src, len);

	return 0;
}