-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmemmalloc.c
79 lines (65 loc) · 1.3 KB
/
memmalloc.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
#include "header.h"
/**
* _realloc - reallocates a memory block using malloc and free
* @ptr: pointer to reallocate memory
* @old_size: size in bytes of allocated memory
* @new_size: newsize of memory block in bytes
*
* Return: void pointer to new allocation of memory
*/
void *_realloc(void *ptr, unsigned int old_size, unsigned int new_size)
{
char *p;
unsigned int i;
if (ptr == NULL)
{
p = safe_malloc(new_size);
return (p);
}
if (new_size == 0)
{
free(ptr);
return (NULL);
}
if (old_size == new_size)
return (ptr);
p = safe_malloc(new_size);
if (p == NULL)
return (NULL);
for (i = 0; i < old_size && i < new_size; i++)
p[i] = ((char *)ptr)[i];
free(ptr);
return (p);
}
/**
* mem_reset - sets all bytes of string to '\0'
* @str: string
* @bytes: number of bytes
*
* Return: pointer to string with reset mem
*/
char *mem_reset(char *str, int bytes)
{
int i = 0;
while (i < bytes)
str[i++] = '\0';
return (str);
}
/**
* safe_malloc - mallocs memory of size bytes, prints error message on error
* @bytes: number of bytes to malloc
*
* Return: pointer to malloced memory or NULL
*/
void *safe_malloc(int bytes)
{
void *check;
check = malloc(bytes);
if (check == NULL)
{
_perror("No Memory\n");
exit(1);
}
check = mem_reset(check, bytes);
return (check);
}