list

Why do program crash sometimes?

*update* without "delete" is working fine!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>

using namespace std;

struct lista
{
 int n;
 lista *next;
};

void inverti (lista* &l)
{
 lista *aux = NULL;
 while (l!=NULL)
 {
  lista *q = new lista;
  q->n = l->n;
  q->next = aux;
  aux = q;
  delete q;
  l = l->next;
 }
 l = aux;
 delete aux;
 return;
}

int main()
{
 lista *l = NULL;

 lista *a = new lista;
 a->n = 3;
 a->next = l;
 l = a;

 lista *b = new lista;
 b->n = 2;
 b->next = l;
 l = b;

 lista *c = new lista;
 c->n = 1;
 c->next = l;
 l = c;

 cout << "Lista:  ";
 lista *s0;
 s0 = l;
 while (s0!=NULL)
 {
  cout << s0->n << " ";
  s0 = s0->next;
 }
 cout << endl;

 inverti(l);

 cout << "Lista:  ";
 lista *s;
 s = l;
 while (s!=NULL)
 {
  cout << s->n << " ";
  s = s->next;
 }
 return 0;
}
Last edited on
> *update* without "delete" is working fine!
no, it leaks memory.
but well, that should give you a hint.


1
2
3
 l = aux; //`l' and `aux' point to the same place
 delete aux; //you destroy whatever `aux' and `l' were pointing to
//here `l' is invalid (can't be dereferenced) 
same error on line 19

by the way, I suggest you to differentiate between a list and a node and make an `insert()' function
Thank you
Topic archived. No new replies allowed.