Search code examples
c++templatesstack-overflow

Finding potential stack overflow issues in templates


I traced a recent crash in my application to a stack overflow problem, and having fixed the problem, I thought I'd do a re-check on the code for any similar potential bugs using the visual studio code analysis tool. This found a number of possible similar cases with a report such as

Warning C6262 Function uses '148140' bytes of stack: exceeds /analyze:stacksize '16384'. Consider moving some data to heap. SCCW-VC2015 c:\cpp\aclcommon\aclcontainer.h

When I look at the code it takes me to the following template function;

template<class TYPE, class ARG_TYPE, class INDEX>
inline INDEX CContainerBase<TYPE, ARG_TYPE, INDEX>::Add(ARG_TYPE newElement)
{ 
    TYPE Temp = newElement; 
    INDEX nIndex = GetSize();
    SetSize(nIndex  + 1);
    SetAt(nIndex,Temp);
    return nIndex; 
}

where the offending line is TYPE Temp = newElement; The problem is that I need to find out which piece of code is using the templated container with such large elements, as the template itself is not the problem. Is there anyway to find out which specific instantiation of the template is in use here, i.e. find out what TYPE refers to?


Solution

  • One approach is to use static_assert on the size of the element inside the template code, like this:

    static_assert(sizeof(TYPE) < 16384, "Object is too large for the stack");
    TYPE Temp = newElement;
    

    This would break a compile in every place where the template is instantiated with a type that is too large for the stack.