-
Notifications
You must be signed in to change notification settings - Fork 9
/
realloc.c
57 lines (53 loc) · 961 Bytes
/
realloc.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
#include "holberton.h"
/**
* _realloc - reallocates a memory block using malloc and free
* @ptr: input pointer
* @old_size: size of old ptr
* @new_size: size of new ptr
* Return: reallocated ptr
*/
void *_realloc(void *ptr, unsigned int old_size, unsigned int new_size)
{
void *res = NULL;
if (new_size == old_size)
return (ptr);
if (!ptr)
{
free(ptr);
res = malloc(new_size);
if (!res)
{
perror("Malloc failed");
exit(errno);
}
return (res);
}
if (!new_size && ptr)
{
free(ptr);
return (NULL);
}
res = malloc(new_size);
if (!res)
{
perror("Malloc failed");
exit(errno);
}
_memcpy(res, ptr, old_size);
free(ptr);
return (res);
}
/**
* _memcpy - copies memory area
* @dest: destination string
* @src: source string
* @n: number of bytes to be copied
* Return: pointer to dest
*/
char *_memcpy(char *dest, char *src, unsigned int n)
{
char *ptr = dest;
while (n--)
*dest++ = *src++;
return (ptr);
}