From 02c78ecf8134fc9961efd3563970672858d503fd Mon Sep 17 00:00:00 2001 From: Daniel Stenberg Date: Thu, 14 Aug 2003 14:19:36 +0000 Subject: allow out-of-memory testing by setting a limit. That number of memory allocation calls will succeed, the following will return NULL! --- lib/memdebug.c | 46 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) (limited to 'lib/memdebug.c') diff --git a/lib/memdebug.c b/lib/memdebug.c index d159fa0f3..088c5cc50 100644 --- a/lib/memdebug.c +++ b/lib/memdebug.c @@ -62,7 +62,10 @@ struct memdebug { * Don't use these with multithreaded test programs! */ -FILE *logfile; +#define logfile curl_debuglogfile +FILE *curl_debuglogfile; +static bool memlimit; /* enable memory limit */ +static long memsize; /* set number of mallocs allowed */ /* this sets the log file name */ void curl_memdebug(const char *logname) @@ -73,12 +76,47 @@ void curl_memdebug(const char *logname) logfile = stderr; } +/* This function sets the number of malloc() calls that should return + successfully! */ +void curl_memlimit(long limit) +{ + memlimit = TRUE; + memsize = limit; +} + +/* returns TRUE if this isn't allowed! */ +static bool countcheck(const char *func, int line, const char *source) +{ + /* if source is NULL, then the call is made internally and this check + should not be made */ + if(memlimit && source) { + if(!memsize) { + if(logfile && source) + fprintf(logfile, "LIMIT %s:%d %s reached memlimit\n", + source, line, func); + return TRUE; /* RETURN ERROR! */ + } + else + memsize--; /* countdown */ + + /* log the countdown */ + if(logfile && source) + fprintf(logfile, "LIMIT %s:%d %ld ALLOCS left\n", + source, line, memsize); + + } + + return FALSE; /* allow this */ +} void *curl_domalloc(size_t wantedsize, int line, const char *source) { struct memdebug *mem; size_t size; + if(countcheck("malloc", line, source)) + return NULL; + /* alloc at least 64 bytes */ size = sizeof(struct memdebug)+wantedsize; @@ -106,6 +144,9 @@ char *curl_dostrdup(const char *str, int line, const char *source) exit(2); } + if(countcheck("strdup", line, source)) + return NULL; + len=strlen(str)+1; mem=curl_domalloc(len, 0, NULL); /* NULL prevents logging */ @@ -125,6 +166,9 @@ void *curl_dorealloc(void *ptr, size_t wantedsize, size_t size = sizeof(struct memdebug)+wantedsize; + if(countcheck("realloc", line, source)) + return NULL; + mem = (struct memdebug *)((char *)ptr - offsetof(struct memdebug, mem)); mem=(struct memdebug *)(realloc)(mem, size); -- cgit v1.2.3