手撕記憶體操作函式

uav360發表於2020-12-22

記憶體複製memcpy

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

void* my_memcpy(void *dest, const void *src, size_t count)
{
    char *tmp = dest;
    const char *s = src;
 
    while(count--){
        *tmp++ = *s++ ;
    }
    
    return dest;
}

int main()
{
    char* buf1 = "abcdefghijklmnopqrstuvwxyz";
    char* buf2 = malloc(27); 

    my_memcpy(buf2,buf1,27);
    printf("buf1 = %s \r\n",buf1);   
    printf("buf2 = %s \r\n",buf2);

    free(buf2);
    return 0;
}

記憶體複製,改進memcpy

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

void* my_memcpy(void *dest, const void *src, size_t count)
{
    char *d;
    const char *s;
 
    if((dest > (src+count)) || (dest < src)){
        d = dest;
        s = src;
        while (count--){
            *d++ = *s++;
        }        
    }else{ /* overlap */
        d = (char *)(dest + count - 1); /* offset of pointer is from 0 */
        s = (char *)(src + count -1);
        while (count --){
            *d-- = *s--;
        }
    }
  
    return dest;
}

int main()
{
    char* buf1 = "abcdefghijklmnopqrstuvwxyz";
    char* buf2 = malloc(27); 

    my_memcpy(buf2,buf1,27);
    printf("buf1 = %s \r\n",buf1);   
    printf("buf2 = %s \r\n",buf2);

    free(buf2);
    return 0;
}

記憶體設定memset

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

void* my_memset(void *s,int c,size_t n)
{
    const unsigned char uc = c;
    unsigned char *su;
    for(su = s;0 < n;++su,--n){
        *su = uc;
    }
		
    return s;
}

int main()
{
    char* buf1 = malloc(6);    
    my_memset(buf1,'1',5);
    buf1[5] = '\0';
    printf("buf1 = %s \r\n", buf1);
    free(buf1);

    char* buf2 = malloc(6);    
    my_memset(buf2,'8',5);
    buf2[5] = '\0';
    printf("buf2 = %s \r\n", buf2);
    free(buf2);

    return 0;
}

相關文章