test_malloc.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. Generic test for malloc/free
  3. */
  4. #include <esp_types.h>
  5. #include <stdio.h>
  6. #include "rom/ets_sys.h"
  7. #include "freertos/FreeRTOS.h"
  8. #include "freertos/task.h"
  9. #include "freertos/semphr.h"
  10. #include "freertos/queue.h"
  11. #include "freertos/xtensa_api.h"
  12. #include "unity.h"
  13. #include "soc/uart_reg.h"
  14. #include "soc/dport_reg.h"
  15. #include "soc/io_mux_reg.h"
  16. #include "esp_heap_caps.h"
  17. #include "esp_panic.h"
  18. #include "sdkconfig.h"
  19. static int **allocatedMem;
  20. static int noAllocated;
  21. static int tryAllocMem() {
  22. int i, j;
  23. const int allocateMaxK=1024*5; //try to allocate a max of 5MiB
  24. allocatedMem=malloc(sizeof(int *)*allocateMaxK);
  25. if (!allocatedMem) return 0;
  26. for (i=0; i<allocateMaxK; i++) {
  27. allocatedMem[i]=malloc(1024);
  28. if (allocatedMem[i]==NULL) break;
  29. for (j=0; j<1024/4; j++) allocatedMem[i][j]=(0xdeadbeef);
  30. }
  31. noAllocated=i;
  32. return i;
  33. }
  34. static void tryAllocMemFree() {
  35. int i, j;
  36. for (i=0; i<noAllocated; i++) {
  37. for (j=0; j<1024/4; j++) {
  38. TEST_ASSERT(allocatedMem[i][j]==(0xdeadbeef));
  39. }
  40. free(allocatedMem[i]);
  41. }
  42. free(allocatedMem);
  43. }
  44. TEST_CASE("Malloc/overwrite, then free all available DRAM", "[heap]")
  45. {
  46. int m1=0, m2=0;
  47. m1=tryAllocMem();
  48. tryAllocMemFree();
  49. m2=tryAllocMem();
  50. tryAllocMemFree();
  51. printf("Could allocate %dK on first try, %dK on 2nd try.\n", m1, m2);
  52. TEST_ASSERT(m1==m2);
  53. }
  54. #if CONFIG_SPIRAM_USE_MALLOC
  55. #if (CONFIG_SPIRAM_MALLOC_RESERVE_INTERNAL > 1024)
  56. TEST_CASE("Check if reserved DMA pool still can allocate even when malloc()'ed memory is exhausted", "[heap]")
  57. {
  58. char** dmaMem=malloc(sizeof(char*)*512);
  59. assert(dmaMem);
  60. int m=tryAllocMem();
  61. int i=0;
  62. for (i=0; i<512; i++) {
  63. dmaMem[i]=heap_caps_malloc(1024, MALLOC_CAP_DMA);
  64. if (dmaMem[i]==NULL) break;
  65. }
  66. for (int j=0; j<i; j++) free(dmaMem[j]);
  67. free(dmaMem);
  68. tryAllocMemFree();
  69. printf("Could allocate %dK of DMA memory after allocating all of %dK of normal memory.\n", i, m);
  70. TEST_ASSERT(i);
  71. }
  72. #endif
  73. #endif