Where's the problem? Is it undefined behavior? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Where's the problem? Is it undefined behavior?

I try to create a container where I can store data like arrays in C++ myself. This code works well on CxxDroid and CppDroid but doesn't work on SoloLearn. Code: https://code.sololearn.com/cRUs8E36ra9a/?ref=app Pictures w/ expect outputs: https://www.sololearn.com/post/221798/?ref=app

17th Jan 2020, 1:24 PM
你知道規則,我也是
你知道規則,我也是 - avatar
3 Answers
+ 3
The problem seems to be your destructor, more specifically that you first delete 'a' and in the next iteration call "a->next", which is an operation on already deleted memory and therefore results in undefined behaviour.
17th Jan 2020, 3:16 PM
Shadow
Shadow - avatar
+ 2
Almost, but I just noticed one other issue I missed earlier. The problem is that when one element is deleted, all the elements after it are also deleted since the destructor call is kind of recursive. To prevent this, you should set in both the destructor and the remove() method the current element's "next" pointer to nullptr right before deleting it so that the following elements are unaffected. This is quite a tricky one and only results in a warning because the SoloLearn compiler seems to regard mutiple deletion of requested memory as something you should not do. This is also why usually in linked list implementations, the data and the pointer to the next element are stored in a separate structure and the list class only handles the nodes but is not part of the list itself.
17th Jan 2020, 9:38 PM
Shadow
Shadow - avatar
0
Shadow/ I have re-coded the destructor. Do I delete the members correctly?
17th Jan 2020, 4:04 PM
你知道規則,我也是
你知道規則,我也是 - avatar