IPP Software Navigation Tools IPP Links Communication Pan-STARRS Links

Ticket #21: example.c

File example.c, 1.3 KB (added by eugene, 22 years ago)

sample code showing use of reference decrementing function, with error caught by psFree

Line 
1
2struct {
3 float f;
4} Foo;
5
6struct {
7 Foo *foo;
8} Bar;
9
10Foo *psFooAlloc () {
11 Foo *foo = (Foo *) psAlloc (1);
12 return (foo);
13}
14
15psFooFree (Foo *foo) {
16 Nref = GetRef (foo);
17 switch (Nref) {
18 case 0:
19 return;
20 case 1:
21 DecrRef (foo);
22 psFree (foo);
23 return;
24 default:
25 DecrRef (foo);
26 return;
27 }
28 return; // cannot reach here
29}
30
31Bar *psBarAlloc () {
32
33 Bar *bar = (Bar *) psAlloc (1);
34 bar[0].foo = NULL;
35
36 return (bar);
37
38}
39
40psBarFree (Bar *bar) {
41 Nref = GetRef (bar);
42 switch (Nref) {
43 case 0:
44 return;
45 case 1:
46 psFooFree (bar[0].foo);
47 DecrRef (bar);
48 psFree (bar);
49 return;
50 default:
51 DecrRef (bar);
52 return;
53 }
54 return; // cannot reach here
55}
56
57Bar *psBarSet (Foo *foo) {
58 Bar *bar = NULL;
59 bar = psBarAlloc ();
60 bar[0].foo = foo;
61 IncrRef (foo);
62}
63
64main.bad () {
65
66 Foo *foo = NULL;
67 Bar *bar = NULL;
68
69 foo = psFooAlloc (); // Nref(foo) = 1
70 bar = psBarSet (foo); // Nref(foo) = 2
71 psFree (foo); // Nref(foo) = 1 ** returns an error **
72 psFree (bar); // Nref(foo) = 1 ** does not free foo **
73}
74
75main.good () {
76
77 Foo *foo = NULL;
78 Bar *bar = NULL;
79
80 foo = psFooAlloc (); // Nref(foo) = 1
81 bar = psBarSet (foo); // Nref(foo) = 2
82 psFooFree (foo); // Nref(foo) = 1
83 psBarFree (bar); // Nref(foo) = 0
84}