jcs
/subtext
/amendments
/112
util: Pre-alloc alert ditl handle, get rid of xmallocarray
calloc does what this did, who knew?
Avoid dynamic allocation in vwarn() so errors about OOM conditions
can succeed
jcs made amendment 112 over 2 years ago
--- util.c Sun May 15 22:16:44 2022
+++ util.c Wed Jun 1 13:11:54 2022
@@ -76,6 +76,20 @@ static TEHandle track_control_te = NULL;
void vwarn(short alert_func, const char *format, va_list ap);
/*
+ * Util helper needed to be called at program startup, to pre-allocate
+ * some things that we can't do during errors.
+ */
+
+void
+util_init(void)
+{
+ alert_ditl_h = xNewHandle(sizeof(alert_ditl));
+ HLock(alert_ditl_h);
+ memcpy(*alert_ditl_h, alert_ditl, sizeof(alert_ditl));
+ HUnlock(alert_ditl_h);
+}
+
+/*
* Memory functions
*/
@@ -86,9 +100,11 @@ xmalloc(size_t size)
if (size == 0)
panic("xmalloc: zero size");
+
ptr = malloc(size);
if (ptr == NULL)
panic("xmalloc(%lu) failed", size);
+
return ptr;
}
@@ -96,7 +112,9 @@ void *
xmalloczero(size_t size)
{
void *ptr = xmalloc(size);
+
memset(ptr, 0, size);
+
return ptr;
}
@@ -108,32 +126,25 @@ xcalloc(size_t nmemb, size_t size)
ptr = calloc(nmemb, size);
if (ptr == NULL)
panic("xcalloc(%lu, %lu) failed", nmemb, size);
+
return ptr;
}
void *
xrealloc(void *src, size_t size)
{
- void *ret;
-
- ret = realloc(src, size);
- if (ret == NULL)
+ void *ptr;
+
+ ptr = realloc(src, size);
+ if (ptr == NULL)
panic("realloc(%lu) failed", size);
- return ret;
+
+ return ptr;
}
#define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))
void *
-xmallocarray(size_t nmemb, size_t size)
-{
- if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
- nmemb > 0 && SIZE_MAX / nmemb < size)
- panic("xmallocarray(%lu, %lu) failed", nmemb, size);
- return xmalloc(size * nmemb);
-}
-
-void *
xreallocarray(void *optr, size_t nmemb, size_t size)
{
if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
@@ -267,11 +278,6 @@ vwarn(short alert_func, const char *format, va_list ap
ParamText(CtoPstr(err_str), "\p", "\p", "\p");
- alert_ditl_h = xNewHandle(sizeof(alert_ditl));
- HLock(alert_ditl_h);
- memcpy(*alert_ditl_h, alert_ditl, sizeof(alert_ditl));
- HUnlock(alert_ditl_h);
-
dialog = NewDialog(nil, &bounds, "\p", false, dBoxProc,
(WindowPtr)-1L, false, 0, alert_ditl_h);
@@ -299,7 +305,6 @@ vwarn(short alert_func, const char *format, va_list ap
break;
}
DisposDialog(dialog);
- DisposHandle(alert_ditl_h);
SetPort(win);
--- util.h Mon May 23 11:59:26 2022
+++ util.h Wed Jun 1 13:12:07 2022
@@ -72,11 +72,12 @@ struct stat {
unsigned char st_flags;
};
+void util_init(void);
+
void * xmalloc(size_t);
void * xmalloczero(size_t);
void * xcalloc(size_t, size_t);
void * xrealloc(void *src, size_t size);
-void * xmallocarray(size_t nmemb, size_t size);
void * xreallocarray(void *, size_t, size_t);
char * xstrdup(const char *);