Graphviz 12.0.1~dev.20240716.0800
Loading...
Searching...
No Matches
vmalloc.c
Go to the documentation of this file.
1/*************************************************************************
2 * Copyright (c) 2011 AT&T Intellectual Property
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * https://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors: Details at https://graphviz.org
9 *************************************************************************/
10
11#include <vmalloc/vmalloc.h>
12#include <stdbool.h>
13#include <stdlib.h>
14#include <string.h>
15
21static bool make_space(Vmalloc_t *vm) {
22
23 if (vm->size == vm->capacity) {
24
25 // expand our allocation storage
26 size_t c = vm->capacity == 0 ? 1 : vm->capacity * 2;
27 void **p = realloc(vm->allocated, sizeof(vm->allocated[0]) * c);
28 if (p == NULL) {
29 return false;
30 }
31
32 // save the new array
33 vm->allocated = p;
34 vm->capacity = c;
35 }
36
37 return true;
38}
39
40void *vmalloc(Vmalloc_t *vm, size_t size) {
41
42 if (!make_space(vm)) {
43 return NULL;
44 }
45
46 void *p = malloc(size);
47 if (p == NULL) {
48 return NULL;
49 }
50
51 vm->allocated[vm->size] = p;
52 ++vm->size;
53
54 return p;
55}
56
57void vmfree(Vmalloc_t *vm, void *data) {
58
59 if (!data) { // ANSI-ism
60 return;
61 }
62
63 // find the pointer we previously allocated
64 for (size_t i = 0; i < vm->size; ++i) {
65 if (vm->allocated[i] == data) {
66
67 // clear this slot
68 size_t extent = sizeof(vm->allocated[0]) * (vm->size - i - 1);
69 memmove(vm->allocated + i, vm->allocated + i + 1, extent);
70 --vm->size;
71
72 // give this back to the underlying allocator
73 free(data);
74
75 return;
76 }
77 }
78
79 // we did not find this pointer; free() of something we did not allocate
80}
void * malloc(YYSIZE_T)
void free(void *)
node NULL
Definition grammar.y:149
void ** allocated
Definition vmalloc.h:27
size_t capacity
Definition vmalloc.h:29
size_t size
Definition vmalloc.h:28
Definition legal.c:50
static bool make_space(Vmalloc_t *vm)
Definition vmalloc.c:21
void vmfree(Vmalloc_t *vm, void *data)
Definition vmalloc.c:57
void * vmalloc(Vmalloc_t *vm, size_t size)
Definition vmalloc.c:40