From: Jeremy Huddleston Date: Sun, 8 May 2011 05:05:16 +0000 (-0700) Subject: Improve error handling in copy_to_scratch X-Git-Tag: xmodmap-1.0.6~6 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=b6b5bc9e9874934dd1c1b80a1aa0c0b1c454eab2;p=platform%2Fupstream%2Fxmodmap.git Improve error handling in copy_to_scratch handle.c:95:5: warning: Array access (from variable 'buf') results in a null pointer dereference buf[len] = '\0'; ^~~ Found-by: clang static analyzer Signed-off-by: Jeremy Huddleston --- diff --git a/handle.c b/handle.c index 737e146..a6e6f9f 100644 --- a/handle.c +++ b/handle.c @@ -82,17 +82,22 @@ copy_to_scratch(const char *s, int len) static char *buf = NULL; static int buflen = 0; - if (len > buflen) { + if (len < 0) + len = 0; + + if (len >= buflen) { if (buf) free (buf); buflen = (len < 40) ? 80 : (len * 2); buf = (char *) malloc (buflen+1); + if (!buf) { + fprintf (stderr, "attempt to allocate %d byte scratch buffer\n", buflen + 1); + return NULL; + } } - if (len > 0) - strncpy (buf, s, len); - else - len = 0; + strncpy (buf, s, len); buf[len] = '\0'; + return (buf); }