Commit 9b6e0d3bd89bb86da40c2cfd5e8271f9236f63e1

Authored by Wiebe Cazemier
1 parent 84e76c32

Fix memory leak on malloc errors

Showing 2 changed files with 19 additions and 4 deletions
client.cpp
@@ -11,11 +11,24 @@ Client::Client(int fd, ThreadData_p threadData) : @@ -11,11 +11,24 @@ Client::Client(int fd, ThreadData_p threadData) :
11 { 11 {
12 int flags = fcntl(fd, F_GETFL); 12 int flags = fcntl(fd, F_GETFL);
13 fcntl(fd, F_SETFL, flags | O_NONBLOCK); 13 fcntl(fd, F_SETFL, flags | O_NONBLOCK);
14 - readbuf = (char*)malloc(CLIENT_BUFFER_SIZE);  
15 - writebuf = (char*)malloc(CLIENT_BUFFER_SIZE); 14 + char *readbuf = (char*)malloc(CLIENT_BUFFER_SIZE);
  15 + char *writebuf = (char*)malloc(CLIENT_BUFFER_SIZE);
16 16
17 if (readbuf == NULL || writebuf == NULL) 17 if (readbuf == NULL || writebuf == NULL)
  18 + {
  19 + if (readbuf != NULL)
  20 + free(readbuf);
  21 + if (writebuf != NULL)
  22 + free(writebuf);
  23 +
  24 + readbuf = NULL;
  25 + writebuf = NULL;
  26 +
18 throw std::runtime_error("Malloc error constructing client."); 27 throw std::runtime_error("Malloc error constructing client.");
  28 + }
  29 +
  30 + this->readbuf = readbuf;
  31 + this->writebuf = writebuf;
19 } 32 }
20 33
21 Client::~Client() 34 Client::~Client()
client.h
@@ -65,9 +65,10 @@ class Client @@ -65,9 +65,10 @@ class Client
65 void growReadBuffer() 65 void growReadBuffer()
66 { 66 {
67 const size_t newBufSize = readBufsize * 2; 67 const size_t newBufSize = readBufsize * 2;
68 - readbuf = (char*)realloc(readbuf, newBufSize); 68 + char *readbuf = (char*)realloc(this->readbuf, newBufSize);
69 if (readbuf == NULL) 69 if (readbuf == NULL)
70 throw std::runtime_error("Memory allocation failure in growReadBuffer()"); 70 throw std::runtime_error("Memory allocation failure in growReadBuffer()");
  71 + this->readbuf = readbuf;
71 readBufsize = newBufSize; 72 readBufsize = newBufSize;
72 73
73 //std::cout << "New read buf size: " << readBufsize << std::endl; 74 //std::cout << "New read buf size: " << readBufsize << std::endl;
@@ -92,11 +93,12 @@ class Client @@ -92,11 +93,12 @@ class Client
92 93
93 const size_t grow_by = std::max<size_t>(add_size, writeBufsize*2); 94 const size_t grow_by = std::max<size_t>(add_size, writeBufsize*2);
94 const size_t newBufSize = writeBufsize + grow_by; 95 const size_t newBufSize = writeBufsize + grow_by;
95 - writebuf = (char*)realloc(writebuf, newBufSize); 96 + char *writebuf = (char*)realloc(this->writebuf, newBufSize);
96 97
97 if (writebuf == NULL) 98 if (writebuf == NULL)
98 throw std::runtime_error("Memory allocation failure in growWriteBuffer()"); 99 throw std::runtime_error("Memory allocation failure in growWriteBuffer()");
99 100
  101 + this->writebuf = writebuf;
100 writeBufsize = newBufSize; 102 writeBufsize = newBufSize;
101 103
102 //std::cout << "New write buf size: " << writeBufsize << std::endl; 104 //std::cout << "New write buf size: " << writeBufsize << std::endl;