alloc.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* Copyright (c) 1991 by the Vrije Universiteit, Amsterdam, the Netherlands.
  2. * For full copyright and restrictions on use see the file COPYING in the top
  3. * level of the LLgen tree.
  4. */
  5. /*
  6. * L L G E N
  7. *
  8. * An Extended LL(1) Parser Generator
  9. *
  10. * Author : Ceriel J.H. Jacobs
  11. */
  12. /*
  13. * alloc.c
  14. * Interface to malloc() and realloc()
  15. */
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. # include "types.h"
  19. # include "extern.h"
  20. # include "LLgen.h"
  21. static string e_nomem = "Out of memory";
  22. p_mem alloc(unsigned int size)
  23. {
  24. /*
  25. Allocate "size" bytes. Panic if it fails
  26. */
  27. p_mem p;
  28. if ((p = malloc(size)) == 0) fatal(linecount,e_nomem, NULL, NULL);
  29. return p;
  30. }
  31. p_mem ralloc(p_mem p, unsigned int size)
  32. {
  33. /*
  34. Re-allocate the chunk of memory indicated by "p", to
  35. occupy "size" bytes
  36. */
  37. if ((p = realloc(p,size)) == 0) fatal(linecount,e_nomem, NULL, NULL);
  38. return p;
  39. }
  40. p_mem new_mem(p_info p)
  41. {
  42. /*
  43. This routine implements arrays that can grow.
  44. It must be called every time a new element is added to it.
  45. Also, the array has associated with it a "info_alloc" structure,
  46. which contains info on the element size, total allocated size,
  47. a pointer to the array, a pointer to the first free element,
  48. and a pointer to the top.
  49. If the base of the array is remembered elsewhere, it should
  50. be updated each time this routine is called
  51. */
  52. p_mem rp;
  53. unsigned int sz;
  54. if (p->i_max >= p->i_top) { /* No more free elements */
  55. sz = p->i_size;
  56. if (sizeof(char *) > 2) {
  57. /*
  58. Do not worry about size. Just double it.
  59. */
  60. p->i_size += p->i_size;
  61. if (! p->i_size)
  62. p->i_size += p->i_incr * p->i_esize;
  63. }
  64. else {
  65. /*
  66. Worry about size, so only increment in chunks of i_incr.
  67. */
  68. p->i_size += p->i_incr * p->i_esize;
  69. }
  70. p->i_ptr = !p->i_ptr ?
  71. alloc(p->i_size) :
  72. ralloc(p->i_ptr, p->i_size);
  73. p->i_max = p->i_ptr + sz;
  74. p->i_top = p->i_ptr + p->i_size;
  75. }
  76. rp = p->i_max;
  77. p->i_max += p->i_esize;
  78. return rp;
  79. }