-
Notifications
You must be signed in to change notification settings - Fork 0
/
atoi_mem.c
91 lines (75 loc) · 1.9 KB
/
atoi_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
91
#include "shell.h"
/**
* _memcpy - copies information between void pointers.
* @newptr: destination pointer.
* @ptr: source pointer.
* @size: size of the new pointer.
*
* Return: no return.
*/
void _memcpy(void *newptr, const void *ptr, unsigned int size)
{
char *char_ptr = (char *)ptr;
char *char_newptr = (char *)newptr;
unsigned int i;
for (i = 0; i < size; i++)
char_newptr[i] = char_ptr[i];
}
/**
* _realloc - reallocates a memory block.
* @ptr: pointer to the memory previously allocated.
* @old_size: size, in bytes, of the allocated space of ptr.
* @new_size: new size, in bytes, of the new memory block.
*
* Return: ptr.
* if new_size == old_size, returns ptr without changes.
* if malloc fails, returns NULL.
*/
void *_realloc(void *ptr, unsigned int old_size, unsigned int new_size)
{
void *newptr;
if (ptr == NULL)
return (malloc(new_size));
if (new_size == 0)
{
free(ptr);
return (NULL);
}
if (new_size == old_size)
return (ptr);
newptr = malloc(new_size);
if (newptr == NULL)
return (NULL);
if (new_size < old_size)
_memcpy(newptr, ptr, new_size);
else
_memcpy(newptr, ptr, old_size);
free(ptr);
return (newptr);
}
/**
* _reallocdp - reallocates a memory block of a double pointer.
* @ptr: double pointer to the memory previously allocated.
* @old_size: size, in bytes, of the allocated space of ptr.
* @new_size: new size, in bytes, of the new memory block.
*
* Return: ptr.
* if new_size == old_size, returns ptr without changes.
* if malloc fails, returns NULL.
*/
char **_reallocdp(char **ptr, unsigned int old_size, unsigned int new_size)
{
char **newptr;
unsigned int i;
if (ptr == NULL)
return (malloc(sizeof(char *) * new_size));
if (new_size == old_size)
return (ptr);
newptr = malloc(sizeof(char *) * new_size);
if (newptr == NULL)
return (NULL);
for (i = 0; i < old_size; i++)
newptr[i] = ptr[i];
free(ptr);
return (newptr);
}