diff src/c/http.c @ 2070:382911d72e63

Check realloc's return code to prevent segfault on out of memory condition (Part 3)
author Sergey Mironov <grrwlf@gmail.com>
date Tue, 02 Sep 2014 17:37:22 +0000
parents 262dd74df39c
children 739172204214
line wrap: on
line diff
--- a/src/c/http.c	Tue Sep 02 17:36:14 2014 +0000
+++ b/src/c/http.c	Tue Sep 02 17:37:22 2014 +0000
@@ -97,8 +97,15 @@
 
       if (back - buf == buf_size - 1) {
         char *new_buf;
-        buf_size *= 2;
-        new_buf = realloc(buf, buf_size);
+        size_t new_buf_size = buf_size*2;
+        new_buf = realloc(buf, new_buf_size);
+        if(!new_buf) {
+          qfprintf(stderr, "Realloc failed while receiving header\n");
+          close(sock);
+          sock = 0;
+          break;
+        }
+        buf_size = new_buf_size;
         back = new_buf + (back - buf);
         buf = new_buf;
       }
@@ -146,9 +153,16 @@
           while (back - body < clen) {
             if (back - buf == buf_size - 1) {
               char *new_buf;
-              buf_size *= 2;
-              new_buf = realloc(buf, buf_size);
+              size_t new_buf_size = buf_size * 2;
+              new_buf = realloc(buf, new_buf_size);
+              if(!new_buf) {
+                qfprintf(stderr, "Realloc failed while receiving content\n");
+                close(sock);
+                sock = 0;
+                goto done;
+              }
 
+              buf_size = new_buf_size;
               back = new_buf + (back - buf);
               body = new_buf + (body - buf);
               s = new_buf + (s - buf);