Among all software vulnerabilities, memory bugs are most common and dangerous. Programs written in unsafe languages such as C and C++ are vulnerable to stack-based buffer overflow, heap buffer overflow, dangling pointer, and double free. Although there are a number of proposed solutions to tolerate heap related bugs, most of the existing solutions terminates the vulnerable program after a stack-based buffer overflow attempt. There is no comprehensive solution to actively tolerate all of the four kinds of bugs mentioned previously currently. This paper presents Memshepherd, a system that can probabilistically prevent software from both stack and heap memory bugs and guarantee soundness of the software execution. It dynamically reallocates stack-based buffers in the heap space during software execution, thus transforms a stack memory problem into a heap memory problem. By adaptively sizing buffers to be M times of their defined size and randomly placing them, Memshepherd keeps the buffers far from each other. When a buffer is to be deallocated, Memshepherd checks invalid and double frees. A Linux prototype is implemented and tested against four kinds of memory bugs. The experiment results prove that Memshepherd is effective in eliminating crashes, erroneous execution, as well as security vulnerability. Copyright © 2013 John Wiley & Sons, Ltd.