-
Notifications
You must be signed in to change notification settings - Fork 0
/
mem.c
90 lines (82 loc) · 1.86 KB
/
mem.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include "string.h"
/**
* _memchr - get the index of the first matching value
* @src: start of the memory area to search
* @chr: value to find
* @n: size of the search area
* Return: If chr does not occur in the first n elements of src, return -1.
* Otherwise, return the index of the first occurence of chr.
*/
ssize_t _memchr(const void *src, unsigned char chr, size_t n)
{
const unsigned char *mem = src;
ssize_t i = 0;
if (src)
{
while (n--)
{
if (mem[i] == chr)
return (i);
i += 1;
}
}
return (-1);
}
/**
* _memcpy - copy a memory area
* @dest: a pointer to the start of the target area
* @src: a pointer to the start of the source area
* @n: the number of bytes to copy
*
* Description: This function copies n bytes from the memory area at src
* to the memory area at dest. These memory areas must not overlap.
*
* Return: a pointer to dest
*/
void *_memcpy(void *dest, const void *src, size_t n)
{
unsigned char *w_pos = dest;
const unsigned char *r_pos = src;
if (dest && src)
{
while (n--)
*w_pos++ = *r_pos++;
}
return (dest);
}
/**
* _memdup - duplicate a memory area
* @src: a pointer to the start of the source area
* @n: the number of bytes to duplicate
* Return: If memory allocation fails, return NULL. Otherwise, return a
* pointer to the start of the duplicated memory.
*/
void *_memdup(const void *src, size_t n)
{
void *dup = malloc(n);
unsigned char *w_pos = dup;
const unsigned char *r_pos = src;
if (dup)
{
while (n--)
*w_pos++ = *r_pos++;
}
return (dup);
}
/**
* _memset - fill a region of memory with a given value
* @dest: pointer to the beginning of the region
* @chr: value to write to the region
* @n: number of bytes to write
* Return: dest
*/
void *_memset(void *dest, unsigned char chr, size_t n)
{
unsigned char *mem = dest;
if (dest)
{
while (n--)
*mem++ = chr;
}
return (dest);
}