Re: STL - Debug assertion failure, vector iterator not dereferencable
John <John@discussions.microsoft.com> wrote:
I recently converted a visual studio .net project to visual studio
2005 project. After
the conversion I am now having runtime errors on a collection that is
composed of a vector of CComVariants.
std::vector<CComVariant> m_vecResults;
More specifically it gives me a Debug assertion failure, vector
iterator not dereferencable in my get__NewEnum method on the Init
statement in the following
code;
STDMETHODIMP get__NewEnum(IUnknown** ppUnk)
{
typedef CComObject<CComEnum<IEnumVARIANT, &IID_IEnumVARIANT,
VARIANT, _Copy<VARIANT> > > enumVariant;
enumVariant* pEnum = new enumVariant;
HRESULT hr = pEnum->Init(&*m_vecResults.begin(),
&*m_vecResults.end(),
0,
AtlFlagCopy );
This code exhibits undefined behavior, and could only ever work by
accident. Specifically, *m_vecResults.end() is illegal - an end()
iterator is not dereferenceable. Try this:
CComVariant* pStart = 0;
CComVariant* pEnd = 0;
if (!m_vecResults.empty()) {
pStart = &m_vecResults.front();
pEnd = pStart + m_vecResults.size();
}
pEnum->Init(pStart, pEnd, ...);
So I modified my code to the following the following to not use
begin/end and it
seemed to of fix the problem.
STDMETHODIMP get__NewEnum(IUnknown** ppUnk)
{
typedef CComObject<CComEnum<IEnumVARIANT, &IID_IEnumVARIANT,
VARIANT, _Copy<VARIANT> > > enumVariant;
size_t nSize = m_vecResults.size();
enumVariant* pEnum = new enumVariant;
HRESULT hr = pEnum->Init(&m_vecResults[0],
&m_vecResults[nSize-1], NULL,
AtlFlagCopy);
This a) doesn't work when the vector is empty, and b) always leaves the
last element out.
Now I have another piece of code that uses a priority queue;
typedef priority_queue< CRfItem, vector< CRfItem >, CRfItem::greater >
RfQueue;
RfQueue m_QueueAllPoints;
I am experiencing the same error again in the following code segment
on the top()
statment;
RfQueue::value_type temp = m_QueueAllPoints.top();
Is the queue empty at this point, by any chance?
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925