Finding potential stack overflow issues in templates

≯℡__Kan透↙ 提交于 2019-12-12 17:47:50

问题


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?


回答1:


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.




回答2:


typeid(TYPE).name() provides a string suitable for debugging, typically the type's name according to the ABI name-mangling rules.



来源:https://stackoverflow.com/questions/42040959/finding-potential-stack-overflow-issues-in-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!