-1

I'm creating linked list with c++ and I allocated list's memory by using "new" every time.

So I have to use delete to prevent memory leak here, but I'm confused with this because I don't know whether I have to use delete or delete[].

Should I regard the linked list as an array?

struct node {
    int data;
    node *next;
};  

I used the code above to make linked list and just like the code you see, I connected the nodes by using pointer.

So.. do I have to use delete, or delete[] to prevent memory leak?

  • hint: if you are wondering whether you can do something trivial, you can begin by trying it, and the compiler will tell you whether it was a good idea or not. Posting a stackoverflow question for something that the compiler can tell you if you just hit the "compile" key is a bit of an overkill. – Mike Nakis Oct 23 '16 at 08:02
  • sorry. I just wanted to be sure.. not that I just wanted to finish my coding but wanted to know the detailed principle for this.. – Hailey K Oct 23 '16 at 08:07
  • [new and delete (C++)](https://en.wikipedia.org/wiki/New_and_delete_(C%2B%2B)) – Anto Jurković Oct 23 '16 at 08:09
  • thanks for the help :) – Hailey K Oct 23 '16 at 08:14
  • 1
    There is an easy way to remember: If you called `new`, then call `delete` but if you called `new[]` then call `delete[]`. – Galik Oct 23 '16 at 08:17
  • thanks for the good tip :D!! – Hailey K Oct 23 '16 at 08:21

1 Answers1

0

To delete the whole list you would have to delete node by node hence using delete

felit
  • 13
  • 3
  • Actually, I'm using for loop and delete to destroy the list's memory but it does not work. – Hailey K Oct 23 '16 at 08:23
  • I called node *p and tried to delete, but it does not work. void destroy(node *p) { for( ; p != NULL ; p = p->next) { delete // for here, what should I do? } } delete p->data cannot work here? – Hailey K Oct 23 '16 at 08:25
  • @HaileyK use `delete p;` – Galik Oct 23 '16 at 08:52