lmem.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. /*
  2. ** $Id: lmem.c,v 1.3 1997/12/01 20:30:44 roberto Exp roberto $
  3. ** Interface to Memory Manager
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <stdlib.h>
  7. #include "lmem.h"
  8. #include "lstate.h"
  9. #include "lua.h"
  10. int luaM_growaux (void **block, unsigned long nelems, int size,
  11. char *errormsg, unsigned long limit)
  12. {
  13. if (nelems >= limit)
  14. lua_error(errormsg);
  15. nelems = (nelems == 0) ? 32 : nelems*2;
  16. if (nelems > limit)
  17. nelems = limit;
  18. *block = luaM_realloc(*block, nelems*size);
  19. return (int)nelems;
  20. }
  21. #ifndef DEBUG
  22. /*
  23. ** generic allocation routine.
  24. ** real ANSI systems do not need some of these tests,
  25. ** since realloc(NULL, s)==malloc(s) and realloc(b, 0)==free(b).
  26. ** But some systems (e.g. Sun OS) are not that ANSI...
  27. */
  28. void *luaM_realloc (void *block, unsigned long size)
  29. {
  30. size_t s = (size_t)size;
  31. if (s != size)
  32. lua_error("Allocation Error: Block too big");
  33. if (size == 0) {
  34. if (block) {
  35. free(block);
  36. }
  37. return NULL;
  38. }
  39. block = block ? realloc(block, s) : malloc(s);
  40. if (block == NULL)
  41. lua_error(memEM);
  42. return block;
  43. }
  44. #else
  45. /* DEBUG */
  46. #include <assert.h>
  47. #include <string.h>
  48. #define MARK 55
  49. unsigned long numblocks = 0;
  50. unsigned long totalmem = 0;
  51. static void *checkblock (void *block)
  52. {
  53. unsigned long *b = (unsigned long *)block - 1;
  54. unsigned long size = *b;
  55. assert(*(((char *)b)+size+sizeof(unsigned long)) == MARK);
  56. numblocks--;
  57. totalmem -= size;
  58. return b;
  59. }
  60. void *luaM_realloc (void *block, unsigned long size)
  61. {
  62. unsigned long realsize = sizeof(unsigned long)+size+sizeof(char);
  63. if (realsize != (size_t)realsize)
  64. lua_error("Allocation Error: Block too big");
  65. if (size == 0) { /* ANSI doen't need this, but some machines... */
  66. if (block) {
  67. memset(block, -1, *((unsigned long *)block-1)); /* erase block */
  68. block = checkblock(block);
  69. free(block);
  70. }
  71. return NULL;
  72. }
  73. if (block) {
  74. block = checkblock(block);
  75. block = (unsigned long *)realloc(block, realsize);
  76. }
  77. else
  78. block = (unsigned long *)malloc(realsize);
  79. if (block == NULL)
  80. lua_error(memEM);
  81. totalmem += size;
  82. numblocks++;
  83. *(unsigned long *)block = size;
  84. *(((char *)block)+size+sizeof(unsigned long)) = MARK;
  85. return (unsigned long *)block+1;
  86. }
  87. #endif