alloc_test.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /*
  2. *
  3. * Copyright 2015 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. #include <grpc/support/alloc.h>
  19. #include <grpc/support/log.h>
  20. #include "test/core/util/test_config.h"
  21. static void* fake_malloc(size_t size) { return (void*)size; }
  22. static void* fake_realloc(void* addr, size_t size) { return (void*)size; }
  23. static void fake_free(void* addr) { *((intptr_t*)addr) = (intptr_t)0xdeadd00d; }
  24. static void test_custom_allocs() {
  25. const gpr_allocation_functions default_fns = gpr_get_allocation_functions();
  26. intptr_t addr_to_free = 0;
  27. char* i;
  28. gpr_allocation_functions fns = {fake_malloc, NULL, fake_realloc, fake_free};
  29. gpr_set_allocation_functions(fns);
  30. GPR_ASSERT((void*)(size_t)0xdeadbeef == gpr_malloc(0xdeadbeef));
  31. GPR_ASSERT((void*)(size_t)0xcafed00d == gpr_realloc(0, 0xcafed00d));
  32. gpr_free(&addr_to_free);
  33. GPR_ASSERT(addr_to_free == (intptr_t)0xdeadd00d);
  34. /* Restore and check we don't get funky values and that we don't leak */
  35. gpr_set_allocation_functions(default_fns);
  36. GPR_ASSERT((void*)sizeof(*i) != (i = gpr_malloc(sizeof(*i))));
  37. GPR_ASSERT((void*)2 != (i = gpr_realloc(i, 2)));
  38. gpr_free(i);
  39. }
  40. int main(int argc, char** argv) {
  41. grpc_test_init(argc, argv);
  42. test_custom_allocs();
  43. return 0;
  44. }