-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrealloc.c
51 lines (48 loc) · 938 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
#include "malloc.h"
pthread_mutex_t lock;
/**
* _realloc - reallocates memory & copies memory to new allocation
* @ptr: pointer to memory for which space to be reallocated
* @size: expected size of new memory allocation
* Return: pointer to allocated memory, NULL upon allocation failure
*/
void *_realloc(void *ptr, size_t size)
{
void *new_mem = NULL;
size_t old_size = 0;
pthread_mutex_lock(&lock);
if (!size)
{
_free(ptr);
pthread_mutex_unlock(&lock);
return (NULL);
}
if (!ptr)
{
new_mem = _malloc(size);
if (!new_mem)
{
pthread_mutex_unlock(&lock);
return (NULL);
}
}
else
{
old_size = (((blockhead *)ptr) - 1)->used_bytes;
if (old_size < size)
{
new_mem = _malloc(size);
if (!new_mem)
{
pthread_mutex_unlock(&lock);
return (NULL);
}
memcpy(new_mem, ptr, old_size);
_free(ptr);
}
else
new_mem = ptr;
}
pthread_mutex_unlock(&lock);
return (new_mem);
}