Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version
Go to top

Tiny C Runtime Library

, 25 Mar 2007
Reduce code bloat for those simple utility programs by using a streamlined C runtime - now with Unicode support!
// memory.cpp

// based on:
// LIBCTINY - Matt Pietrek 2001
// MSDN Magazine, January 2001

// 08/13/06 (mv)

#include <windows.h>
#include <string.h>
#include "libct.h"

BEGIN_EXTERN_C

int memcmp(const void *b1, const void *b2, size_t n)
{
	const unsigned char *p1 = (const unsigned char*)b1;
	const unsigned char *p2 = (const unsigned char*)b2;

	if (!n)
		return 0;
	for (size_t i = 0; i < n; i++)
	{
		if (p1[i] != p2[i])
			return p1[i]-p2[i];
	}
	return 0;
}

void *memset(void *dst, int val, size_t size)
{
	char *realdst = (char*)dst;
	for (size_t i = 0; i < size; i++)
		realdst[i] = (char)val;
	return dst;
}

void *memcpy(void *dst, const void *src, size_t size)
{
	char *_dst = (char*)dst;
	const char *_src = (char*)src;
	for (size_t i = 0; i < size; i++)
		_dst[i] = _src[i];
	return dst;
}

void *memmove(void *dst, const void *src, size_t count)
{
	void *ret = dst;
	if (dst <= src || (char *)dst >= ((char *)src + count))
	{
		// Non-Overlapping Buffers
		// copy from lower addresses to higher addresses
		while (count--)
		{
			*(char*)dst = *(char*)src;
			dst = (char*)dst + 1;
			src = (char*)src + 1;
		}
	}
	else
	{
		// Overlapping Buffers
		// copy from higher addresses to lower addresses
		dst = (char*)dst + count - 1;
		src = (char*)src + count - 1;

		while (count--)
		{
			*(char*)dst = *(char*)src;
			dst = (char*)dst - 1;
			src = (char*)src - 1;
		}
	}

	return ret;
}

END_EXTERN_C

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Mike_V

United States United States
Mike_V is currently a student at UCLA.
 
After a few years on the Dark Side, he reformed and now chants "Death to VB." His computer-related interests include C++, C#, and ASP.NET (in C#, of course). He writes operating systems in C++ and assembler as a hobby.

| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 25 Mar 2007
Article Copyright 2006 by Mike_V
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid