What is the proper way to duplicate the soops->tree and then use the duplicate as a replacement?

I am experimenting with sorting and filtering the Outliner, and my altered Blender has suffered an exception:

Exception thrown: read access violation.
te was 0xFFFFFFFFFFFFFFCF

------------------My questions are ----------------------------

Question: Why is te becoming NULL at function
bool outliner_is_collection_tree_element(const TreeElement *te) ?

Question: What is the proper way to duplicate the soops->tree and then use the duplicate in place of the current soops->tree ?

-------------Here is the explanation of my code AND my actual code I have written(note that I believe that all of my code below is simple and straightforward)-----------------

In my code I duplicate the soops->tree that is within function outliner_build_tree(). I ultimately use BLI_duplicatelist() to duplicate inside my function duplicate_tree().

I then free the original soops->tree using my function outliner_free_source_tree()

Then I attempt to replace the original with the allocated duplicated ListBase tree_dup; by assigning the first/last members to soops->tree

soops->tree.first = tree_dup.first;
soops->tree.last = tree_dup.last;

THE CODE:

https://pastebin.com/RsEvX9CZ

I figured out the problem and solution. It was obvious.

BLI_duplicatelist() naturally sets duplicate_element–>parent = source_element–>parent. This was not my desired behavior. So duplicate_element–>parent has to be set correctly outside of BLI_duplicatelist()

When I freed the source soops->tree elements it, inadvertently , also freed the duplicate tree_dup parent elements. So all of the duplicate_element–>parent ended up NULL