Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
APIsWithLua/ch6/limit_memory.c
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
52 lines (40 sloc)
1.02 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // limit_memory.c | |
| // | |
| #include "interpreter.h" | |
| #include "lauxlib.h" | |
| #include "lua.h" | |
| #include "lualib.h" | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <sys/errno.h> | |
| long bytes_alloced = 0; | |
| long max_bytes = 30000; // You can choose this value. | |
| void *alloc(void *ud, | |
| void *ptr, | |
| size_t osize, | |
| size_t nsize) { | |
| // Compute the byte change requested. May be negative. | |
| long num_bytes_to_add = nsize - (ptr ? osize : 0); | |
| // Reject the change if it would exceed our limit. | |
| if (bytes_alloced + num_bytes_to_add > max_bytes) { | |
| errno = ENOMEM; | |
| return NULL; | |
| } | |
| // Otherwise, free or allocate memory as requested. | |
| bytes_alloced += num_bytes_to_add; | |
| if (nsize) return realloc(ptr, nsize); | |
| free(ptr); | |
| return NULL; | |
| } | |
| void print_status() { | |
| printf("%ld bytes allocated\n", bytes_alloced); | |
| } | |
| int main() { | |
| lua_State *L = lua_newstate(alloc, NULL); | |
| luaL_openlibs(L); | |
| print_status(); | |
| while (accept_and_run_a_line(L)) print_status(); | |
| lua_close(L); | |
| print_status(); | |
| return 0; | |
| } |