strdup的原理以及用法

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

char* strDUP(char* str)
{
	int len = strlen(str);
	if(len <=0 )
		return NULL;

	char* p = (char*)malloc(len+1);
	memset( p, 0, len+1);
	memcpy( p, str, len);

	return p;
}


int main(int argc, char* argv[])
{
	char* str = "this is a demo for strdup()";

	char* p = strDUP(str);


	printf(p);
	printf("\n");

	free(p);

	return 0;
}

你可能感兴趣的:(strdup的原理以及用法)