1 /*****************************************************************************\
5 **---------------------------------------------------------------------------**
6 ** Copyright: Andreas Eversberg **
8 ** Macros to do safe string operations to avoid buffer overflows **
9 ** Macros for memory allocation, feeing and error handling **
11 \*****************************************************************************/
14 /* save strcpy/strncpy */
16 #define SCPY(dst, src) scpy(dst, src, sizeof(dst))
17 extern __inline__ void scpy(char *dst, char *src, unsigned int siz)
19 strncpy(dst, src, siz);
23 /* save strcat/strncat */
25 #define SCAT(dst, src) scat(dst, src, sizeof(dst))
26 extern __inline__ void scat(char *dst, char *src, unsigned int siz)
28 strncat(dst, src, siz);
32 /* save concat of a byte */
34 #define SCCAT(dst, src) sccat(dst, src, sizeof(dst))
35 extern __inline__ void sccat(char *dst, char chr, unsigned int siz)
37 if (strlen(dst) < siz-1)
39 dst[strlen(dst)+1] = '\0';
40 dst[strlen(dst)] = chr;
44 /* save sprintf/snprintf */
46 #define SPRINT(dst, fmt, arg...) sprint(dst, sizeof(dst), fmt, ## arg)
47 extern __inline__ void sprint(char *dst, unsigned int siz, char *fmt, ...)
52 vsnprintf(dst, siz, fmt, args);
62 #define UPRINT sprintf
63 #define UNPRINT snprintf
64 #define VUNPRINT vsnprintf
66 /* fatal error with error message and exit */
67 #define FATAL(fmt, arg...) fatal(__FUNCTION__, __LINE__, fmt, ##arg)
68 extern __inline__ void fatal(const char *function, int line, char *fmt, ...)
74 vsnprintf(buffer, sizeof(buffer), fmt, args);
76 buffer[sizeof(buffer)-1] = '\0';
77 fprintf(stderr, "FATAL ERROR in function %s, line %d: %s", function, line, buffer);
78 fprintf(stderr, "This error is not recoverable, must exit here.\n");
80 debug(function, line, "FATAL ERROR", buffer);
81 debug(function, line, "FATAL ERROR", "This error is not recoverable, must exit here.\n");
86 /* memory allocation with setting to zero */
87 #define MALLOC(size) _malloc(size, __FUNCTION__, __LINE__)
88 extern __inline__ void *_malloc(unsigned long size, const char *function, int line)
93 fatal(function, line, "No memory for %d bytes.\n", size);
94 memset(addr, 0, size);
98 /* memory freeing with clearing memory to prevent using freed memory */
99 #define FREE(addr, size) _free(addr, size)
100 extern __inline void _free(void *addr, int size)
103 memset(addr, 0, size);