- memcpy
Function: Starting from the starting position of the memory address pointed to by src, copy count bytes of data to the starting position of the memory address pointed to by the target dest.
#include <stdio.h> #include<assert.h> void* my_memcpy(void* dest,const void* src,size_t count){ assert(dest); assert(src); void* ret = dest; while(count--){ *(char*)dest = *(char*)src; dest = (char *) dest + 1; src = (char*)src+1; } return ret; } int main(){ char buf[] = "abcdefghigk"; my_memcpy(buf+2,buf,5); printf("%s\n",buf+2); return 0; }
- memmove
Function: Copy count bytes from the memory area pointed to by src to the memory area pointed to by dest.
#include <stdio.h> #include<assert.h> #include<string.h> void* my_memmove(void* dest,const void* src,size_t count){ assert(dest); assert(src); void* ret = dest; if(dest <= src || (char*)dest >= ((char*)src+count)){ while(count--){ *(char*)dest = *(char*)src; dest = (char *) dest + 1; src = (char*)src+1; } } else{ dest = (char *) dest + count-1; src = (char*)src+count-1; while(count--){ *(char*)dest = *(char*)src; dest = (char *) dest-1; src = (char*)src-1; } } return ret; } int main(){ char s[] = "hello world"; my_memmove(s,s+3,strlen(s)+1-3); printf("%s\n",s); return 0; }
- memset
#include <stdio.h> #include<assert.h> void* my_memset(void* dest,int c,size_t count){ assert(dest); if(count < 0) return NULL; char * tmp = (char *) dest; while(count--) *tmp++ = c; return dest; } int main(){ char buf[10]; int i = 0; printf("sizeof(buf) = %d\n",sizeof(buf)); for(i = 0;i < 10;i++) printf("buf[%d] = %d\n",i,buf[i]); printf("-----------------------------------\n"); my_memset(buf,1,sizeof(buf)); for(i = 0;i < 10;i++) printf("buf[%d] = %d\n",i,buf[i]); return 0; }
- memcmp
Function: Compare the first num bytes of ptr1 and ptr2 in the memory area.
#include <stdio.h> #include<assert.h> int my_memcmp(const void* ptr1,const void* ptr2,size_t num){ assert(ptr1); assert(ptr2); while(num--){ while(*(char*)ptr1 == *(char*)ptr2){ if(*(char*)ptr1 == '\0') return 0; ptr1++; ptr2++; } } if(*(char*)ptr1 > *(char*)ptr2) return 1; else if(*(char*)ptr1 < *(char*)ptr2) return -1; } int main(){ char* p = "adcc"; char* q = "axcc"; printf("%d\n",my_memcmp(p,q,3)); return 0; }
- memchr
Function: Find the character c from the first count bytes of the memory area pointed to by buf
#include <stdio.h> #include<assert.h> #include<string.h> void* memchr(const void* buf,int c,size_t count){ assert(buf); while(count--){ if(*(char*)buf == (char)c) return (void*)buf; buf = (char*)buf+1; } return NULL; } int main(){ char* pch; char str[] = "hello world"; pch = (char*)memchr(str,'w',strlen(str)); if(pch != NULL) printf("fpund at position %d\n",pch-str+1); else printf("not found\n"); return 0; }