diff --git a/include/libtorrent/stack_allocator.hpp b/include/libtorrent/stack_allocator.hpp index f12f4cb91..2fdd4c4f3 100644 --- a/include/libtorrent/stack_allocator.hpp +++ b/include/libtorrent/stack_allocator.hpp @@ -62,6 +62,7 @@ namespace libtorrent { namespace aux int copy_buffer(char const* buf, int size) { int ret = int(m_storage.size()); + if (size < 1) return -1; m_storage.resize(ret + size); memcpy(&m_storage[ret], buf, size); return ret; @@ -69,6 +70,7 @@ namespace libtorrent { namespace aux int allocate(int bytes) { + if (bytes < 1) return -1; int ret = int(m_storage.size()); m_storage.resize(ret + bytes); return ret; @@ -76,14 +78,14 @@ namespace libtorrent { namespace aux char* ptr(int idx) { - TORRENT_ASSERT(idx >= 0); + if(idx < 0) return NULL; TORRENT_ASSERT(idx < int(m_storage.size())); return &m_storage[idx]; } char const* ptr(int idx) const { - TORRENT_ASSERT(idx >= 0); + if(idx < 0) return NULL; TORRENT_ASSERT(idx < int(m_storage.size())); return &m_storage[idx]; } diff --git a/test/test_stack_allocator.cpp b/test/test_stack_allocator.cpp index 62b1971f2..90f07f380 100644 --- a/test/test_stack_allocator.cpp +++ b/test/test_stack_allocator.cpp @@ -59,6 +59,14 @@ TORRENT_TEST(copy_buffer) a.allocate(100000); TEST_CHECK(strcmp(a.ptr(idx1), "testing") == 0); + + // attempt zero size allocation + int const idx2 = a.copy_buffer("nothing", 0); + TEST_CHECK(idx2 == -1); + + // attempt to get a pointer after zero allocation + char* ptr = a.ptr(idx2); + TEST_CHECK(ptr == NULL); } TORRENT_TEST(allocate) @@ -75,6 +83,14 @@ TORRENT_TEST(allocate) ptr = a.ptr(idx1); for (int i = 0; i < 100; ++i) TEST_CHECK(ptr[i] == char(i % 256)); + + // attempt zero size allocation + int const idx2 = a.allocate(0); + TEST_CHECK(idx2 == -1); + + // attempt to get a pointer after zero allocation + ptr = a.ptr(idx2); + TEST_CHECK(ptr == NULL); } TORRENT_TEST(swap)