Search code examples
c++pointersbreakpoints

Cant delete pointer, has triggered a breakpoint


I learned C++ in on online course, but have a problem with a "delete" statement, in Visual Studio. When delete is executed, it opens a file delete_scalar.cpp and shows:

ConsoleApplication.exe has triggered a breakpoint. exception thrown

I already move the SymbolCache folder from temp, including wntdll.pdb etc.

#include "pch.h"
#include <iostream>
using namespace std;

int main()
{
int *pInt = new int;
*pInt = 3;
cout << *pInt << endl;
cout << pInt << endl;

delete[] pInt; //error -- UPDATED: still get error with `delete pInt;` 

return 0;
}

here the output info,

'ConsoleApplication11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ntdll.dll'. Symbols loaded. 'ConsoleApplication11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\kernel32.dll'. Symbols loaded. 'ConsoleApplication11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\KernelBase.dll'. Symbols loaded. 'ConsoleApplication11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcp140d.dll'. Symbols loaded. 'ConsoleApplication11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\vcruntime140d.dll'. Symbols loaded. 'ConsoleApplication11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ucrtbased.dll'. Symbols loaded. The thread 0x2fd0 has exited with code 0 (0x0). HEAP[ConsoleApplication11.exe]: Invalid address specified to RtlValidateHeap( 00930000, 009359E8 ) ConsoleApplication11.exe has triggered a breakpoint.

delete_scalar.cpp from the visual itself,

//
// delete_scalar.cpp
//
//      Copyright (c) Microsoft Corporation. All rights reserved.
//
// Defines the scalar operator delete.
//
#include <crtdbg.h>
#include <malloc.h>
#include <vcruntime_new.h>
#include <vcstartup_internal.h>

_CRT_SECURITYCRITICAL_ATTRIBUTE
void __CRTDECL operator delete(void* const block) noexcept
{
    #ifdef _DEBUG
    _free_dbg(block, _UNKNOWN_BLOCK); // the circle X symbol showed up there
    #else
    free(block);
    #endif
}

I already do the breakpoint things like enable and deleting, but the breakpoint still triggered on the delete_scalar.cpp with circle X symbol showing up.


Solution

  • If you ask for memory with new, you need to delete it with delete.

    Only use delete [ ] when you used new [ ]. Mismatching the two leads to undefined behavior.