1 /* debug_alloc.h
2  *
3  * Some macros which can report on malloc results.
4  *
5  * Enable with "-D DEBUG_ALLOC"
6  */
7 
8 #ifndef DEBUG_ALLOC_H
9 #define DEBUG_ALLOC_H
10 
11 #include <stdio.h>
12 
13 // Debug calls
14 
15 #ifdef CORTEX_M4
16 extern char * __heap_end;
17 register char * sp asm ("sp");
18 #endif
19 
DEBUG_MALLOC(const char * func,size_t size)20   static inline void * DEBUG_MALLOC(const char *func, size_t size) {
21     void *ptr = malloc(size);
22     fprintf(stderr, "MALLOC: %s %p %d", func, ptr, (int)size);
23 #ifdef CORTEX_M4
24 
25     fprintf(stderr, " : sp %p ", sp);
26 #endif
27     if (!ptr) fprintf(stderr, " ** FAILED **");
28     fprintf(stderr, "\n");
29     return(ptr);
30     }
31 
DEBUG_CALLOC(const char * func,size_t nmemb,size_t size)32   static inline void * DEBUG_CALLOC(const char *func, size_t nmemb, size_t size) {
33     void *ptr = calloc(nmemb, size);
34     fprintf(stderr, "CALLOC: %s %p %d %d", func, ptr, (int)nmemb, (int)size);
35 #ifdef CORTEX_M4
36     fprintf(stderr, " : sp %p ", sp);
37 #endif
38     if (!ptr) fprintf(stderr, " ** FAILED **");
39     fprintf(stderr, "\n");
40     return(ptr);
41     }
DEBUG_FREE(const char * func,void * ptr)42   static inline void DEBUG_FREE(const char *func, void *ptr) {
43     free(ptr);
44     fprintf(stderr, "FREE: %s %p\n", func, ptr);
45     }
46 
47 #ifdef DEBUG_ALLOC
48   #define MALLOC(size) DEBUG_MALLOC(__func__, size)
49   #define CALLOC(nmemb, size) DEBUG_CALLOC(__func__, nmemb, size)
50   #define FREE(ptr) DEBUG_FREE(__func__, ptr)
51 #else //DEBUG_ALLOC
52 // Default to normal calls
53   #define MALLOC(size) malloc(size)
54 
55   #define CALLOC(nmemb, size) calloc(nmemb, size)
56 
57   #define FREE(ptr) free(ptr)
58 
59 #endif //DEBUG_ALLOC
60 
61 #endif //DEBUG_ALLOC_H
62