UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

#1 2006-05-12 03:44 PM

Lloyd
Member
Registered: 2006-02-13
Posts: 53

Re: Delete

Offline

#2 2006-05-15 09:02 AM

Nope
Administrator
From: Germany
Registered: 2004-01-24
Posts: 385
Website

Re: Delete

As a struct in c++ is basically nothing else than a class with only public components, you can/should use a destructor to take care of the clean up. It is also a good idea to initialise the used variables. Like this:

struct Data
{
	Data() { a=b=0; c=NULL; next=NULL }
	~Data() { if(c!=NULL) delete [] c; }

	int a;
	int b;
	char *c;
	struct Data *next;
}

main()
{
	Data *x;

	x=new Data;

	x->c=new char[500];

	// some code

	delete x;
}

Offline

#3 2006-05-25 08:40 AM

Lloyd
Member
Registered: 2006-02-13
Posts: 53

Re: Delete

This post is irrelevant to the previous one.

Is this is a right way to delete nodes in a linked list?

struct list* x;
for(node=head->next;node!=NULL;node=node->next)
{
  x=node;
  node=node->next;
  delete x;
}
delete head;

Offline

#4 2006-05-25 11:11 AM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: Delete

No, it isn't. You do twice "node = node->next", so you only free up half of the nodes (but it will probably segfault anyway). I'd probably do something like:

struct list* x;
node = head;
while (node){
    x=node;
    node=node->next;
    delete x;
}

Offline

#5 2006-05-28 03:49 PM

Uzume
Administrator
Registered: 2002-08-30
Posts: 186

Re: Delete

Or if you really want or like the "for" loop construct...

struct list *head, *node, *x;
for (node = head; node; node = x) {
  x = node->next;
  delete node;
}

Offline

Board footer

Powered by FluxBB