-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path100-realloc.c
50 lines (41 loc) · 1012 Bytes
/
100-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
#include "main.h"
/**
* _realloc - reallocates a memory block using malloc and free
* @ptr: a pointer to the memory previously allocated with malloc
* @old_size: the size, in bytes, of the allocated space for ptr
* @new_size: the new size, in bytes, of the new memory block
*
* Return: If the function fails - returns NULL
* Otherwise - returns a pointer to the newly allocated memory block.
*/
void *_realloc(void *ptr, unsigned int old_size, unsigned int new_size)
{
void *new_ptr;
unsigned int i, min_size;
if (new_size == 0 && ptr != NULL)
{
free(ptr);
return (NULL);
}
if (old_size > new_size)
min_size = new_size;
else
min_size = old_size;
if (new_size == old_size)
return (ptr);
if (ptr == NULL)
{
new_ptr = malloc(new_size);
return (new_ptr);
}
if (new_size > old_size)
{
new_ptr = malloc(new_size);
if (new_ptr == NULL)
return (NULL);
}
for (i = 0; i < min_size; i++)
*((char *) new_ptr + i) = *((char *) ptr + i);
free(ptr);
return (new_ptr);
}