Single linked list

前端 未结 7 794
無奈伤痛
無奈伤痛 2021-01-23 13:54

I have created a single linked list. Everything works fine.

I just want to know if I have done anything potentially dangerous in my code. The code snippets I am concern

7条回答
  •  太阳男子
    2021-01-23 13:59

    From pop()

                if(head->product_code == code)
                {
                        temp = head;
                        head = head->next;
                        free(temp);
    
                        // Finished Deleting product
                        return;
                }
    

    In the case of there only being one item, 'head' and 'tail' would be pointing to the same node. However, if you pop this one item, 'head' will be adjusted but 'tail' will still be pointing to the free'd node. This will leave a bad pointer, which may cause your computer to explode.

    Addendum: Similarly, 'new_product' will be dangling if you ever pop the last node that was pushed, and clean_up() will leave the 'tail' pointer dangling as well. Even if the code sample provided will never dereference these after they're free'd, dangling pointers in C code should always be treated as "potentially dangerous".

提交回复
热议问题