c++模板定义malloc

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_41913666/article/details/82585485

用模板定义一个简单的malloc

#define _CRT_SECURE_NO_WARNINGS//不推荐

//#include <stdlib.h>

//static void *(*c_malloc)(size_t sz) = malloc;

//自定义模板开辟指针内存
namespace mzs {

	template<class T>
	T t_malloc(int i) {
		T t = (T)malloc(sizeof(T)*i);
		//T t = (T)c_malloc(sizeof(T)*i);
		return t;
	}
}



#include <iostream>

using namespace std;

int main(int argc, char const *argv[])
{
        //malloc调用
	char* test = "test";
	char* str = (char*)malloc(sizeof(char*) * 20);
	cout << "str:" << strlen(str) << endl;
	strcpy_s(str, strlen(test) + 1, test);
	cout << "str:" << str << endl;
	free(str); str = NULL;

	//模板显示调用
	char *ptr = mzs::t_malloc<char *>(20);
	int len = strlen(ptr);
	cout << "ptr:" << len << endl;
	strcpy_s(ptr, strlen(test) + 1, test);//推荐strcpy_s
	cout << "ptr:" << ptr << endl;
	free(ptr); ptr = NULL;
	
	unsigned char *c = mzs::t_malloc<unsigned char *>(10);
	cout << "c:" << strlen((char*)c) << endl;
	strcpy((char*)c, test);//不推荐strcpy。
	cout << "c:" << c << endl;
	free(c); c = NULL;

	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_41913666/article/details/82585485
今日推荐