lmem.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. /*
  2. ** $Id: lmem.c,v 1.6 1998/06/19 16:14:09 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 <string.h>
  47. #define HEADER (sizeof(double))
  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 *)((char *)block - HEADER);
  54. unsigned long size = *b;
  55. LUA_ASSERT(*(((char *)b)+size+HEADER) == MARK,
  56. "corrupted block");
  57. numblocks--;
  58. totalmem -= size;
  59. return b;
  60. }
  61. void *luaM_realloc (void *block, unsigned long size)
  62. {
  63. unsigned long realsize = HEADER+size+1;
  64. if (realsize != (size_t)realsize)
  65. lua_error("Allocation Error: Block too big");
  66. if (size == 0) { /* ANSI dosen't need this, but some machines... */
  67. if (block) {
  68. unsigned long *b = (unsigned long *)((char *)block - HEADER);
  69. memset(block, -1, *b); /* erase block */
  70. block = checkblock(block);
  71. free(block);
  72. }
  73. return NULL;
  74. }
  75. if (block) {
  76. block = checkblock(block);
  77. block = (unsigned long *)realloc(block, realsize);
  78. }
  79. else
  80. block = (unsigned long *)malloc(realsize);
  81. if (block == NULL)
  82. lua_error(memEM);
  83. totalmem += size;
  84. numblocks++;
  85. *(unsigned long *)block = size;
  86. *(((char *)block)+size+HEADER) = MARK;
  87. return (unsigned long *)((char *)block+HEADER);
  88. }
  89. #endif