alloc.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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 <stdlib.h>
  17. # include "types.h"
  18. # include "extern.h"
  19. # ifndef NORCSID
  20. static string rcsid = "$Id$";
  21. # endif
  22. static string e_nomem = "Out of memory";
  23. p_mem
  24. alloc(size) unsigned size; {
  25. /*
  26. Allocate "size" bytes. Panic if it fails
  27. */
  28. p_mem p;
  29. if ((p = malloc(size)) == 0) fatal(linecount,e_nomem);
  30. return p;
  31. }
  32. p_mem
  33. ralloc(p,size) p_mem p; unsigned size; {
  34. /*
  35. Re-allocate the chunk of memory indicated by "p", to
  36. occupy "size" bytes
  37. */
  38. if ((p = realloc(p,size)) == 0) fatal(linecount,e_nomem);
  39. return p;
  40. }
  41. p_mem
  42. new_mem(p) register p_info p; {
  43. /*
  44. This routine implements arrays that can grow.
  45. It must be called every time a new element is added to it.
  46. Also, the array has associated with it a "info_alloc" structure,
  47. which contains info on the element size, total allocated size,
  48. a pointer to the array, a pointer to the first free element,
  49. and a pointer to the top.
  50. If the base of the array is remembered elsewhere, it should
  51. be updated each time this routine is called
  52. */
  53. p_mem rp;
  54. unsigned sz;
  55. if (p->i_max >= p->i_top) { /* No more free elements */
  56. sz = p->i_size;
  57. if (sizeof(char *) > 2) {
  58. /*
  59. Do not worry about size. Just double it.
  60. */
  61. p->i_size += p->i_size;
  62. if (! p->i_size)
  63. p->i_size += p->i_incr * p->i_esize;
  64. }
  65. else {
  66. /*
  67. Worry about size, so only increment in chunks of i_incr.
  68. */
  69. p->i_size += p->i_incr * p->i_esize;
  70. }
  71. p->i_ptr = !p->i_ptr ?
  72. alloc(p->i_size) :
  73. ralloc(p->i_ptr, p->i_size);
  74. p->i_max = p->i_ptr + sz;
  75. p->i_top = p->i_ptr + p->i_size;
  76. }
  77. rp = p->i_max;
  78. p->i_max += p->i_esize;
  79. return rp;
  80. }