初试断言

#include <stdio.h>

#include <stdlib.h>



//#define NDEBUG	//禁用NDBUG

#include <assert.h>

typedef unsigned char byte;



#define DEBUG	//自定义的断言宏





/* memcpy ─── 拷贝不重叠的内存块*/

void* memcpy(void* pvTo, void* pvFrom, size_t size)

{

	byte* pbTo = (byte*)pvTo;

	byte* pbFrom = (byte*)pvFrom;

	if(pvTo == NULL || pvFrom == NULL)

	{

		fprintf(stderr, "Bad args in memcpy\n");

		abort();

	}

	while(size-->0)

		*pbTo++ = *pbFrom++;

	return(pvTo);

}







void* memcpy2(void* pvTo, void* pvFrom, size_t size)

{

	byte* pbTo = (byte*)pvTo;

	byte* pbFrom = (byte*)pvFrom;

#ifdef DEBUG

	if(pvTo == NULL || pvFrom == NULL)

	{

		fprintf(stderr, "Bad args in memcpy\n");

		abort();

	}

#endif

	while(size-->0)

		*pbTo++ = *pbFrom++;

	return(pvTo);

}





void* memcpy3(void* pvTo, void* pvFrom, size_t size)

{

	byte* pbTo = (byte*)pvTo;

	byte* pbFrom = (byte*)pvFrom;

	assert(NULL != pvTo && NULL != pvFrom );

	while(size-->0)

		*pbTo++ = *pbFrom++;

	return(pvTo);

}







#ifdef DEBUG

void _Assert(char* , unsigned); /* 原型*/

#define ASSERT(f) \

	if(f) \

	NULL; \

	else \

	_Assert(__FILE__ , __LINE__)//这个宏定义不能放在表达式当中

#else

#define ASSERT(f) NULL

#endif



void _Assert(char* strFile, unsigned uLine)

{

	fflush(stdout);

	fprintf(stderr, "\nAssertion failed: %s, line %u\n",strFile, uLine);

	fflush(stderr);

	abort();

}



void* memcpy4(void* pvTo, void* pvFrom, size_t size)

{

	byte* pbTo = (byte*)pvTo;

	byte* pbFrom = (byte*)pvFrom;

	ASSERT(NULL != pvTo && NULL != pvFrom );

	while(size-->0)

		*pbTo++ = *pbFrom++;

	return(pvTo);

}





/* memcpy ─── 拷贝不重叠的内存块*/

void* memcpy5(void* pvTo, void* pvFrom, size_t size)

{

	byte* pbTo = (byte*)pvTo;

	byte* pbFrom = (byte*)pvFrom;

	ASSERT(NULL != pvTo && NULL != pvFrom );	//要使用断言对函数参数进行确认

	ASSERT(pbFrom+size <= pbTo || pbTo+size <= pbFrom);	/* 内存块重叠吗?如果重叠,就使用memmove */

	while(size-->0)

		*pbTo++ = *pbFrom++;

	return(pvTo);

}





const int len = 20;



int main()

{

	char *pchFrom = new char[len];

	pchFrom[0] = 's';

	pchFrom[1] = '\0';

	char *pchTo = NULL;

	//memcpy3(pchTo, pchFrom,len);

	//memcpy4(pchTo, pchFrom,len);

	memcpy5(pchTo, pchFrom,len);

	return 0;

}

你可能感兴趣的:(断言)