Itseez/opencv — pull request #3106 by LeszekSwirski (2014-08-14 15:12:10+00:00)
Title: Fix reallocation of D buffer in gemm

In `cv::gemm`, there is an issue when

1. The matrices are large (are multiplied in blocks + AutoBuffer allocates them on the heap), and
2. One of the inputs is also the output.

In this case, the [working buffer `buf` is allocated to make space for the result](https://github.com/Itseez/opencv/blob/257463719b1657f66e1886f2007a6d609ce58aa2/modules/core/src/matmul.cpp#L1136), but then is [reallocated to perform the block operations](https://github.com/Itseez/opencv/blob/257463719b1657f66e1886f2007a6d609ce58aa2/modules/core/src/matmul.cpp#L1273), deleting the result storage. Potentially this wasn't observed before because in low memory pressure cases the deallocated memory may not actually be re-used by the OS

This PR fixes this issue by delaying the buffer allocation until it knows how much scratch space it needs, and in the case where block scratch spaces is needed, appends the result matrix space onto the end of that.

This issue is also present in 2.4, I can rebase on top of that if that's preferred.

(Not an easy bug to find btw)