void removeDuplicateWithHashtable(LinkedListElement<char> *head)
{
LinkedListElement<char> *runner = head;
LinkedListElement<char> *previous = nullptr;
hash_map<char, bool> record;
while (runner) {
if (record.count(runner->Data) == 0) {
pair<char, bool> item(runner->Data,true);
record.insert(item);
}else
{
free(runner);
previous->Next = runner->Next;
}
previous=runner;
runner=runner->Next;
}
}
Initially I thought there would be an error. Because in free(runner), if i free the memory, i can not access runner->Next.
But GCC compiler ran successfully.
Actually if i change free to delete runner, it is also correct.
can i ask the reason may be free or delete just tell you the memory is available no actually clear data inside, so you can also access Next.
And can i ask how to improve it?
It is not a compilation error but the problem (undefined behaviour) will manifest itself at runtime. If you choose to call
freeon unallocated memory the compiler will not stop you.