-
Notifications
You must be signed in to change notification settings - Fork 1
/
malloc_functions.c
executable file
·74 lines (71 loc) · 1.23 KB
/
malloc_functions.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
#include "monty.h"
/**
* _calloc - concatenate two strings specially
* @nmemb: number of elements
* @size: type of elements
* Return: nothing
*/
void *_calloc(unsigned int nmemb, unsigned int size)
{
void *p = NULL;
unsigned int i;
if (nmemb == 0 || size == 0)
{
return (NULL);
}
p = malloc(nmemb * size);
if (p == NULL)
{
return (NULL);
}
for (i = 0; i < (nmemb * size); i++)
{
*((char *)(p) + i) = 0;
}
return (p);
}
/**
* _realloc - change the size and copy the content
* @ptr: malloc pointer to reallocate
* @old_size: old number of bytes
* @new_size: new number of Bytes
* Return: nothing
*/
void *_realloc(void *ptr, unsigned int old_size, unsigned int new_size)
{
char *p = NULL;
unsigned int i;
if (new_size == old_size)
return (ptr);
if (ptr == NULL)
{
p = malloc(new_size);
if (!p)
return (NULL);
return (p);
}
if (new_size == 0 && ptr != NULL)
{
free(ptr);
return (NULL);
}
if (new_size > old_size)
{
p = malloc(new_size);
if (!p)
return (NULL);
for (i = 0; i < old_size; i++)
p[i] = *((char *)ptr + i);
free(ptr);
}
else
{
p = malloc(new_size);
if (!p)
return (NULL);
for (i = 0; i < new_size; i++)
p[i] = *((char *)ptr + i);
free(ptr);
}
return (p);
}