alloc.c 2.0 KB

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