delete problem

Hi! I have a problem with delete. This is my function. When it comes to delete q my program is breaking down. What could it be the problema?
1
2
3
4
5
6
void sterge_prim(nod *&prim)
{
	nod *q=prim;
	prim=prim->urm;
	delete q;
}
i dont think you can delocate that memory since you didnt dynamically created by using new keyword. Take my response with a grain of salt i'm just reading about pointers. I might be wrong.
Last edited on
You only need delete memory that you allocated using new.

I note that you don't actually do anything with q after you create it; is there more to this function that you've left out?
Last edited on
No, there isn't any more.
Please write me the algorithm to eliminate the first element of a list. That's what i'm trying to do with my function.
Thank you for your prompt answer.

How is each nod object created?
1
2
3
4
5
struct nod
{
     int info;
     nod *next;
}
Is each nod object created on the stack, or is memory dynamically allocated with new or malloc ?
It is dynamically allocated.
How is it dynamically allocated?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int main()
{
	nod *first,*last;
	scanf("%d",&x);
	first->info=x;first->next=NULL;last=first;
	scanf("%d",&x);
	while(x)
	{
		add_after_last(last);
		scanf("%d",&x);
	}
}
void add_after_last(nod *&last)
{
        nod *p=new nod;
        p->info=x;p->next=NULL;
        last->next=p;
        last=p;
}


Something like this.
1
2
3
nod *first,*last;
	scanf("%d",&x);
	first->info=x;first->next=NULL;last=first;


This is stomping all over the random piece of memory that first is pointing to; nod *first,*last; does not create two nod objects, it creates two pointers that could be pointing anywhere, and then you're writing into that memory.

If you try to delete first; , you'll have a problem, as you never allocated it with new
Last edited on
I have got the idea.
Thank you a lot and I'm sorry because you spent your precious time with such a banal thing.
Topic archived. No new replies allowed.