-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path100-realloc.c
56 lines (44 loc) · 1.08 KB
/
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
51
52
53
54
55
56
#include "main.h"
#include <stdlib.h>
/**
* _realloc - Reallocates a memory block using malloc and free.
* @ptr: A pointer to the memory previously allocated with a call to 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 new_size equals old_size - ptr.
* If new_size equals 0 and ptr is not NULL - NULL.
* Else - a pointer to the reallocated memory block.
*/
void *_realloc(void *ptr, unsigned int old_size, unsigned int new_size)
{
void *mem;
char *ptr_copy, *filler;
unsigned int index;
if (new_size == old_size)
return (ptr);
if (ptr == NULL)
{
mem = malloc(new_size);
if (mem == NULL)
return (NULL);
return (mem);
}
if (new_size == 0 && ptr != NULL)
{
free(ptr);
return (NULL);
}
ptr_copy = ptr;
mem = malloc(sizeof(*ptr_copy) * new_size);
if (mem == NULL)
{
free(ptr);
return (NULL);
}
filler = mem;
for (index = 0; index < old_size && index < new_size; index++)
filler[index] = *ptr_copy++;
free(ptr);
return (mem);
}