Question

I have this code:

class Vards 
{
    public:
    char vards[31];
    //some functions here//
};

Vards *Arr;
Arr = new Vards[word_count];//dynamically allocates 

//do some stuff

delete[] Arr;

And everything seems to be fine, but upon the last line VS gives me an exception and breaks to some strange places like:

extern "C" _CRTIMP int __cdecl _CrtIsValidHeapPointer(
        const void * pUserData
        )
{
        if (!pUserData)
            return FALSE;

        if (!_CrtIsValidPointer(pHdr(pUserData), sizeof(_CrtMemBlockHeader), FALSE))
            return FALSE;

        return HeapValidate( _crtheap, 0, pHdr(pUserData) );
}

And then to

void __cdecl _free_base (void * pBlock)
{

        int retval = 0;


        if (pBlock == NULL)
            return;

        RTCCALLBACK(_RTC_Free_hook, (pBlock, 0));

        retval = HeapFree(_crtheap, 0, pBlock);
        if (retval == 0)
        {
            errno = _get_errno_from_oserr(GetLastError());
        }
}

Is this supposed to be normal? My CodeBlocks can't even run the program (although it compiles it) so I am wonder if there is something I am doing wrong. I can't google anything that would relate to this. Are there some kind of limitations with object arrays, or am I doing something wrong?

[EDIT] Based on Matts and barak manos advice, I thoroughly checked entire code and found that indeed I was acessing the array with a too large index in one specific place. Could please one of you post your comment as an answer so I can mark this answered?

Bonus question: If I did some damage to heap before deleting a)Why didn't it find it immediately? b)How does it find it upon deletion?

Était-ce utile?

La solution

As others have commented, you probably are corrupting the heap somewhere. (Someone who commented this should make it an answer so they can take the credit.)

About your bonus questions: When you write to an element of an array (for speed) there is no checking whether the index in within bounds in C and C++. (Of course, you will get a segmentation error is you try to write to memory that doesn't belong to you.)

Before and after the memory you get from new[], several specially formatted bytes are allocated for bookkeeping. When you use delete[], the validity of those bytes will be checked to detect a corrupt heap. If I'm not mistaken, if and how this works depends on your platform and compiler.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top