Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* ************************************************************************** */
- /* LE - / */
- /* / */
- /* gc_like.c .:: .:/ . .:: */
- /* +:+:+ +: +: +:+:+ */
- /* By: aviscogl <aviscogl@student.le-101.fr> +:+ +: +: +:+ */
- /* #+# #+ #+ #+# */
- /* Created: 2018/01/08 13:50:10 by aviscogl #+# ## ## #+# */
- /* Updated: 2018/01/08 16:37:56 by aviscogl ### #+. /#+ ###.fr */
- /* / */
- /* / */
- /* ************************************************************************** */
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct s_heap {
- void **heap;
- size_t size;
- } t_heap;
- void ft_bzero(void *s, size_t n)
- {
- size_t i;
- i = 0;
- while (i < n)
- {
- ((char *)s)[i] = 0;
- i++;
- }
- }
- void *ft_memalloc(size_t size)
- {
- void *str;
- str = (void*)malloc(sizeof(void*) * size);
- if (str == NULL)
- return (NULL);
- ft_bzero(str, sizeof(void *) * size);
- return (str);
- }
- t_heap *get_heap(void)
- {
- static t_heap *hp = NULL;
- if (!hp)
- {
- hp = malloc(sizeof(t_heap));
- hp->size = 10;
- hp->heap = ft_memalloc(hp->size);
- }
- return (hp);
- }
- void heap_up()
- {
- t_heap *hp;
- void **tmp;
- int i;
- hp = get_heap();
- i = -1;
- tmp = ft_memalloc(hp->size * 2);
- while (++i < hp->size)
- tmp[i] = hp->heap[i];
- free(hp->heap);
- hp->size *= 2;
- hp->heap = tmp;
- }
- void **get_first_empty()
- {
- const t_heap *hp = get_heap();
- int i;
- i = -1;
- while (++i < hp->size)
- {
- if (hp->heap[i] == NULL)
- return (hp->heap + i);
- }
- heap_up();
- return (get_first_empty());
- }
- void *m_malloc(size_t size)
- {
- void *ptr;
- void **pos_tab;
- pos_tab = get_first_empty();
- if ((ptr = malloc(size)) == NULL)
- return (NULL);
- *pos_tab = ptr;
- return (ptr);
- }
- int m_free(void *s)
- {
- const t_heap *hp = get_heap();
- int i;
- int contain;
- i = -1;
- contain = 0;
- while (++i < hp->size)
- {
- if (hp->heap[i] == s)
- {
- contain = 1;
- break ;
- }
- }
- if (!contain)
- return (0);
- free(s);
- hp->heap[i] = NULL;
- return (1);
- }
- void free_all()
- {
- t_heap *hp;
- int i;
- hp = get_heap();
- i = -1;
- while (++i < hp->size)
- if (hp->heap[i] != NULL)
- free(hp->heap[i]);
- free(hp->heap);
- free((t_heap *)hp);
- hp->heap = NULL;
- hp = NULL;
- }
- int main(void)
- {
- int i = -1;
- int count = 0;
- while (++i < 100)
- {
- int *a = m_malloc(sizeof(int) * 3);
- a[0] = count++;
- a[1] = count++;
- a[2] = count++;
- printf(" - %i %i %i\n", a[0], a[1], a[2]);
- }
- free_all();
- }
Add Comment
Please, Sign In to add comment