1

I've been working on trying to create a singly linked list in C++ on Visual Studio but keep running into this weird bug. When I test the list everything works perfectly fine in testing except when it comes to deleting the list. For some reason whenever I call delete on it, I get a popup from Visual Studio with the following messages in this order:

Debug Assertion Failed! Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)

Debug Assertion Failed! Expression: _CtrilsValidHeapPointer(pUserData)

Debug Assertion Failed! Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)

The way I designed the list, head is a pointer to a dummy node that does not hold any data members. Here is the code wwhich was found to be causing problems:

int main() {
SSLL<char> list;
list.push_back('A');
delete &list;
}
Code
  • 151
  • 1
  • 1
  • 9
  • Show how you're adding nodes – Marco A. Oct 09 '14 at 13:56
  • I just added it. Thanks for looking over it! – Code Oct 09 '14 at 13:59
  • The comment seems fine, can you also add the construction and destruction of the list? – Marco A. Oct 09 '14 at 14:04
  • I just did. I appreciate you taking the time to look over this. – Code Oct 09 '14 at 14:18
  • Wow I just caught it. I never actually created an object to delete since I didn't intiialize with new... Thank you for helping to direct me in that direction! Wow after staring at my class code for so long I can't believe it was something in the main.cpp file. Thanks so much! You're awesome! – Code Oct 09 '14 at 14:24

2 Answers2

1

This is the problem:

int main() {
  SSLL<char> list;
  list.push_back('A');
  delete &list; // WRONG!
}

your class is a stack local object, you don't need to call delete on its address: it will automatically be destroyed when it gets out-of-scope.

Code
  • 151
  • 1
  • 1
  • 9
Marco A.
  • 43,032
  • 26
  • 132
  • 246
0

You are trying to delete variable allocated on stack, you should call delete only on the memory allocated by new, this was already covered in this answer.

Perhaps you wanted to use std::vector::clear() just to erase list (although it's not necessary, memory gets freed by vectors destructor).

Community
  • 1
  • 1
Vyktor
  • 20,559
  • 6
  • 64
  • 96