-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_realloc.c
44 lines (36 loc) · 1004 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
#include "shell.h"
/**
* _realloc - allocate memory and set all values to 0
* @ptr: pointer to the memory previously allocated (malloc(old_size))
* @old_size: size previously allocated
* @new_size: new size to reallocate
* Return: pointer to reallocated memory
*/
void *_realloc(void *ptr, unsigned int old_size, unsigned int new_size)
{
void *p;
unsigned int i;
if (new_size == 0 && ptr != NULL) /* free memory if reallocate 0 */
{
free(ptr);
return (NULL);
}
if (new_size == old_size) /* return ptr if reallocating same old size */
return (ptr);
if (ptr == NULL) /* malloc new size if ptr is originally null */
{
p = malloc(new_size);
if (p == NULL)
return (NULL);
else
return (p);
}
p = malloc(new_size); /* malloc and check error */
if (p == NULL)
return (NULL);
/* fill up values up till minimum of old or new size */
for (i = 0; i < old_size && i < new_size; i++)
*((char *)p + i) = *((char *)ptr + i);
free(ptr); /* free old ptr */
return (p);
}