lmem.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. /*
  2. ** $Id: lmem.c,v 1.8 1999/01/22 17:28:00 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. /*
  11. ** real ANSI systems do not need some of these tests,
  12. ** since realloc(NULL, s)==malloc(s).
  13. ** But some systems (Sun OS) are not that ANSI...
  14. */
  15. #ifdef OLD_ANSI
  16. #define realloc(b,s) ((b) == NULL ? malloc(s) : (realloc)(b, s))
  17. #define free(b) if (b) (free)(b)
  18. #endif
  19. int luaM_growaux (void **block, unsigned long nelems, int size,
  20. char *errormsg, unsigned long limit) {
  21. if (nelems >= limit)
  22. lua_error(errormsg);
  23. nelems = (nelems == 0) ? 32 : nelems*2;
  24. if (nelems > limit)
  25. nelems = limit;
  26. *block = luaM_realloc(*block, nelems*size);
  27. return (int)nelems;
  28. }
  29. #ifndef DEBUG
  30. /*
  31. ** generic allocation routine.
  32. */
  33. void *luaM_realloc (void *block, unsigned long size) {
  34. size_t s = (size_t)size;
  35. if (s != size)
  36. lua_error("Allocation Error: Block too big");
  37. if (size == 0) {
  38. free(block); /* block may be NULL, that is OK for free */
  39. return NULL;
  40. }
  41. block = realloc(block, s);
  42. if (block == NULL)
  43. lua_error(memEM);
  44. return block;
  45. }
  46. #else
  47. /* DEBUG */
  48. #include <string.h>
  49. #define HEADER (sizeof(double))
  50. #define MARK 55
  51. unsigned long numblocks = 0;
  52. unsigned long totalmem = 0;
  53. static void *checkblock (void *block) {
  54. unsigned long *b = (unsigned long *)((char *)block - HEADER);
  55. unsigned long size = *b;
  56. LUA_ASSERT(*(((char *)b)+size+HEADER) == MARK,
  57. "corrupted block");
  58. numblocks--;
  59. totalmem -= size;
  60. return b;
  61. }
  62. void *luaM_realloc (void *block, unsigned long size) {
  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) {
  67. if (block) {
  68. unsigned long *b = (unsigned long *)((char *)block - HEADER);
  69. memset(block, -1, *b); /* erase block */
  70. block = checkblock(block);
  71. }
  72. free(block);
  73. return NULL;
  74. }
  75. if (block)
  76. block = checkblock(block);
  77. block = (unsigned long *)realloc(block, realsize);
  78. if (block == NULL)
  79. lua_error(memEM);
  80. totalmem += size;
  81. numblocks++;
  82. *(unsigned long *)block = size;
  83. *(((char *)block)+size+HEADER) = MARK;
  84. return (unsigned long *)((char *)block+HEADER);
  85. }
  86. #endif