-
Notifications
You must be signed in to change notification settings - Fork 13
/
learn-c-the-hard-waych33.txt
619 lines (549 loc) · 21 KB
/
learn-c-the-hard-waych33.txt
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
Learn C The Hard Way A Learn Code The Hard Way Book
* Book
* Comments
* Video Courses
* Related Books
[next] [prev] [prev-tail] [tail] [up]
Chapter 33
Exercise 32: Double Linked Lists
The purpose of this book is to teach you how your computer really
works, and included in that is how various data structures and
algorithms function. Computers by themselves don't do a lot of useful
processing. To make them do useful things you need to structure the
data and then organize processing on these structures. Other
programming languages either include libraries that implement all of
these structures, or they have direct syntax for them. C makes you
implement all the data structures you need yourself, which makes it the
perfect language to learn how they actually work.
My goal in teaching you these data structures and these algorithms is
to help you do three things:
1. Understand what is really going on in Python, Ruby, or JavaScript
code like: data = {"name": "Zed"}
2. Get even better at C code by applying what you know to a set of
solved problems using the data structures.
3. Learn a core set of data structures and algorithms so that you are
better informed about what ones work best in certain situations.
33.1 What Are Data Structures
The name "data structure" is self-explanatory. It is an organization of
data that fits a certain model. Maybe the model is designed to allow
processing the data in a new way. Maybe it's just organized to store it
on disk efficiently. In this book I'll follow a simple pattern for
making data structures that works reliably:
1. Define a struct for the main "outer structure".
2. Define a struct for the contents, usually nodes with links between
them.
3. Create functions that operate on these two.
There's other styles of data structures in C, but this pattern works
well and is consistent for most data structures you'll make.
33.2 Making The Library
For the rest of this book you'll be creating a library that you can use
when you're done with this book. This library will have the following
elements:
1. Header (.h) files for each data structure.
2. Implementation (.c) files for the algorithms.
3. Unit tests that test all of them to make sure they keep working.
4. Documentation we'll autogenerate from the header files.
You already have the c-skeleton so use it to create a liblcthw project:
__________________________________________________________________
Source 93: ex32.sh-session
1 $ cp -r c-skeleton liblcthw
2 $ cd liblcthw/
3 $ ls
4 LICENSE Makefile README.md bin build src tests
5 $ vim Makefile
6 $ ls src/
7 dbg.h libex29.c libex29.o
8 $ mkdir src/lcthw
9 $ mv src/dbg.h src/lcthw
10 $ vim tests/minunit.h
11 $ rm src/libex29.* tests/libex29*
12 $ make clean
13 rm -rf build tests/libex29_tests
14 rm -f tests/tests.log
15 find . -name "*.gc*" -exec rm {} \;
16 rm -rf `find . -name "*.dSYM" -print`
17 $ ls tests/
18 minunit.h runtests.sh
19 $
__________________________________________________________________
In this session I'm doing the following:
1. Copy the c-skeleton over.
2. Edit the Makefile to change libYOUR_LIBRARY.a to liblcthw.a as the
new TARGET.
3. Make the src/lcthw directory where we'll put our code.
4. Move the src/dbg.h into this new directory.
5. Edit tests/minunit.h so that it uses #include <lcthw/dbg.h> as the
include.
6. Get rid of the source and test files we don't need for libex29.*.
7. Clean up everything that's left over.
With that you're ready to start building the library, and the first
data structure I'll build is the Double Linked List.
33.3 Double Linked Lists
The first data structure we'll add to liblcthw is a double linked list.
This is the simplest data structure you can make, and it has useful
properties for certain operations. A linked list works by nodes having
pointers to their next or previous element. A "double linked list"
contains pointers to both, while a "single linked list" only points at
the next element.
Because each node has pointers to the next and previous, and because
you keep track of the first and last element of the list, you can do
some operations very quickly. Anything that involves inserting or
deleting an element will be very fast. They are also easy to implement
by most people.
The main disadvantage of a linked list is that traversing it involves
processing every single pointer along the way. This means that
searching, most sorting, or iterating over the elements will be slow.
It also means that you can't really jump to random parts of the list.
If you had an array of elements you could just index right into the
middle of the list, but a linked list uses a stream of pointers. That
means if you want the 10th element, you have to go through elements
1-9.
33.3.1 Definition
As I said in the introduction to this exercise, the process to follow
is to first write a header file with the right C struct statements in
it.
__________________________________________________________________
Source 94: src/lcthw/list.h
1 #ifndef lcthw_List_h
2 #define lcthw_List_h
3
4 #include <stdlib.h>
5
6 struct ListNode;
7
8 typedef struct ListNode {
9 struct ListNode *next;
10 struct ListNode *prev;
11 void *value;
12 } ListNode;
13
14 typedef struct List {
15 int count;
16 ListNode *first;
17 ListNode *last;
18 } List;
19
20 List *List_create();
21 void List_destroy(List *list);
22 void List_clear(List *list);
23 void List_clear_destroy(List *list);
24
25 #define List_count(A) ((A)->count)
26 #define List_first(A) ((A)->first != NULL ? (A)->first->value : NUL
L)
27 #define List_last(A) ((A)->last != NULL ? (A)->last->value : NULL)
28
29 void List_push(List *list, void *value);
30 void *List_pop(List *list);
31
32 void List_shift(List *list, void *value);
33 void *List_unshift(List *list);
34
35 void *List_remove(List *list, ListNode *node);
36
37 #define LIST_FOREACH(L, S, M, V) ListNode *_node = NULL;\
38 ListNode *V = NULL;\
39 for(V = _node = L->S; _node != NULL; V = _node = _node->M)
40
41 #endif
__________________________________________________________________
The first thing I do is create two structs for the ListNode and the
List that will contain those nodes. This creates the data structure
I'll use in the functions and macros I define after that. If you read
through these functions they seem rather simple. I'll be explaining
them when I cover the implementation, but hopefully you can guess what
they do.
How the data structure works is each ListNode has three components:
1. A value, which is a pointer to anything and stores the thing we
want to put in the list.
2. A ListNode *next pointer which points at another ListNode that
holds the next element in the list.
3. A ListNode *prev that holds the previous element. Complex right?
Calling the previous thing "previous". I could have used "anterior"
and "posterior" but only a jerk would do that.
The List struct is then nothing more than a container for these
ListNode structs that have been linked together in a chain. It keeps
track of the count, first and last element of the list.
Finally, take a look at src/lcthw/list.h:37 where I define the
LIST_FOREACH macro. This is a common idiom where you make a macro that
generates iteration code so people can't mess it up. Getting this kind
of processing right can be difficult with data structures, so writing
macros helps people out. You'll see how I use this when I talk about
the implementation.
33.3.2 Implementation
Once you understand that, you mostly understand how a double linked
list works. It is nothing more than nodes with two pointers to the next
and previous element of the list. You can then write the
src/lcthw/list.c code to see how each operation is implemented.
__________________________________________________________________
Source 95: src/lcthw/list.c
1 #include <lcthw/list.h>
2 #include <lcthw/dbg.h>
3
4 List *List_create()
5 {
6 return calloc(1, sizeof(List));
7 }
8
9 void List_destroy(List *list)
10 {
11 LIST_FOREACH(list, first, next, cur) {
12 if(cur->prev) {
13 free(cur->prev);
14 }
15 }
16
17 free(list->last);
18 free(list);
19 }
20
21
22 void List_clear(List *list)
23 {
24 LIST_FOREACH(list, first, next, cur) {
25 free(cur->value);
26 }
27 }
28
29
30 void List_clear_destroy(List *list)
31 {
32 List_clear(list);
33 List_destroy(list);
34 }
35
36
37 void List_push(List *list, void *value)
38 {
39 ListNode *node = calloc(1, sizeof(ListNode));
40 check_mem(node);
41
42 node->value = value;
43
44 if(list->last == NULL) {
45 list->first = node;
46 list->last = node;
47 } else {
48 list->last->next = node;
49 node->prev = list->last;
50 list->last = node;
51 }
52
53 list->count++;
54
55 error:
56 return;
57 }
58
59 void *List_pop(List *list)
60 {
61 ListNode *node = list->last;
62 return node != NULL ? List_remove(list, node) : NULL;
63 }
64
65 void List_shift(List *list, void *value)
66 {
67 ListNode *node = calloc(1, sizeof(ListNode));
68 check_mem(node);
69
70 node->value = value;
71
72 if(list->first == NULL) {
73 list->first = node;
74 list->last = node;
75 } else {
76 node->next = list->first;
77 list->first->prev = node;
78 list->first = node;
79 }
80
81 list->count++;
82
83 error:
84 return;
85 }
86
87 void *List_unshift(List *list)
88 {
89 ListNode *node = list->first;
90 return node != NULL ? List_remove(list, node) : NULL;
91 }
92
93 void *List_remove(List *list, ListNode *node)
94 {
95 void *result = NULL;
96
97 check(list->first && list->last, "List is empty.");
98 check(node, "node can't be NULL");
99
100 if(node == list->first && node == list->last) {
101 list->first = NULL;
102 list->last = NULL;
103 } else if(node == list->first) {
104 list->first = node->next;
105 check(list->first != NULL, "Invalid list, somehow got a fi
rst that is NULL.");
106 list->first->prev = NULL;
107 } else if (node == list->last) {
108 list->last = node->prev;
109 check(list->last != NULL, "Invalid list, somehow got a nex
t that is NULL.");
110 list->last->next = NULL;
111 } else {
112 ListNode *after = node->next;
113 ListNode *before = node->prev;
114 after->prev = before;
115 before->next = after;
116 }
117
118 list->count--;
119 result = node->value;
120 free(node);
121
122 error:
123 return result;
124 }
__________________________________________________________________
I then implement all of the operations on a double linked list that
can't be done with simple macros. Rather than cover every tiny little
line of this file, I'm going to give high-level overview of every
operation in both the list.h and list.c file, then leave you to read
the code.
list.h:List_count
Returns the number of elements in the list, which is maintained
as elements are added and removed.
list.h:List_first
Returns the first element of the list, but does not remove it.
list.h:List_last
Returns the last element of the list, but does not remove it.
list.h:LIST_FOREACH
Iterates over the elements in the list.
list.c:List_create
Simply creates the main List struct.
list.c:List_destroy
Destroys a List and any elements it might have.
list.c:List_clear
Convenience function for freeing the values in each node, not
the nodes.
list.c:List_clear_destroy
Clears and destroys a list. It's not very efficient since it
loops through them twice.
list.c:List_push
The first operation that demonstrates the advantage of a linked
list. It adds a new element to the end of the list, and because
that's just a couple of pointer assignments, does it very fast.
list.c:List_pop
The inverse of List_push, this takes the last element off and
returns it.
list.c:List_shift
The other thing you can easily do to a linked list is add
elements to the front of the list very fast. In this case I call
that List_shift for lack of a better term.
list.c:List_unshift
Just like List_pop, this removes the first element and returns
it.
list.c:List_remove
This is actually doing all of the removal when you do List_pop
or List_unshift. Something that seems to always be difficult in
data structures is removing things, and this function is no
different. It has to handle quite a few conditions depending on
if the element being removed is at the front; the end; both
front and end; or middle.
Most of these functions are nothing special, and you should be able to
easily digest this and understand it from just the code. You should
definitely focus on how the LIST_FOREACH macro is used in List_destroy
so you can understand how much it simplifies this common operation.
33.4 Tests
After you have those compiling it's time to create the test that makes
sure they operate correctly.
__________________________________________________________________
Source 96: tests/list_tests.c
1 #include "minunit.h"
2 #include <lcthw/list.h>
3 #include <assert.h>
4
5 static List *list = NULL;
6 char *test1 = "test1 data";
7 char *test2 = "test2 data";
8 char *test3 = "test3 data";
9
10
11 char *test_create()
12 {
13 list = List_create();
14 mu_assert(list != NULL, "Failed to create list.");
15
16 return NULL;
17 }
18
19
20 char *test_destroy()
21 {
22 List_clear_destroy(list);
23
24 return NULL;
25
26 }
27
28
29 char *test_push_pop()
30 {
31 List_push(list, test1);
32 mu_assert(List_last(list) == test1, "Wrong last value.");
33
34 List_push(list, test2);
35 mu_assert(List_last(list) == test2, "Wrong last value");
36
37 List_push(list, test3);
38 mu_assert(List_last(list) == test3, "Wrong last value.");
39 mu_assert(List_count(list) == 3, "Wrong count on push.");
40
41 char *val = List_pop(list);
42 mu_assert(val == test3, "Wrong value on pop.");
43
44 val = List_pop(list);
45 mu_assert(val == test2, "Wrong value on pop.");
46
47 val = List_pop(list);
48 mu_assert(val == test1, "Wrong value on pop.");
49 mu_assert(List_count(list) == 0, "Wrong count after pop.");
50
51 return NULL;
52 }
53
54 char *test_shift()
55 {
56 List_shift(list, test1);
57 mu_assert(List_first(list) == test1, "Wrong first value.");
58
59 List_shift(list, test2);
60 mu_assert(List_first(list) == test2, "Wrong first value");
61
62 List_shift(list, test3);
63 mu_assert(List_first(list) == test3, "Wrong last value.");
64 mu_assert(List_count(list) == 3, "Wrong count on shift.");
65
66 return NULL;
67 }
68
69 char *test_remove()
70 {
71 // we only need to test the middle remove case since push/shift
72 // already tests the other cases
73
74 char *val = List_remove(list, list->first->next);
75 mu_assert(val == test2, "Wrong removed element.");
76 mu_assert(List_count(list) == 2, "Wrong count after remove.");
77 mu_assert(List_first(list) == test3, "Wrong first after remove.
");
78 mu_assert(List_last(list) == test1, "Wrong last after remove.")
;
79
80 return NULL;
81 }
82
83
84 char *test_unshift()
85 {
86 char *val = List_unshift(list);
87 mu_assert(val == test3, "Wrong value on unshift.");
88
89 val = List_unshift(list);
90 mu_assert(val == test1, "Wrong value on unshift.");
91 mu_assert(List_count(list) == 0, "Wrong count after unshift.");
92
93 return NULL;
94 }
95
96
97
98 char *all_tests() {
99 mu_suite_start();
100
101 mu_run_test(test_create);
102 mu_run_test(test_push_pop);
103 mu_run_test(test_shift);
104 mu_run_test(test_remove);
105 mu_run_test(test_unshift);
106 mu_run_test(test_destroy);
107
108 return NULL;
109 }
110
111 RUN_TESTS(all_tests);
__________________________________________________________________
This test simply goes through every operation and makes sure it works.
I use a simplification in the test where I create just one List *list
for the whole program, then have the tests work on it. This saves the
trouble of building a List for every test, but it could mean that some
tests only pass because of how the previous test ran. In this case I
try to make each test keep the list clear or actually use the previous
test's results.
33.5 What You Should See
If you did everything right, then when you do a build and run the unit
tests it should look like this:
__________________________________________________________________
Source 97: Ex32 Session
1 $ make
2 cc -g -O2 -Wall -Wextra -Isrc -rdynamic -DNDEBUG -fPIC -c -o src/
lcthw/list.o src/lcthw/list.c
3 ar rcs build/liblcthw.a src/lcthw/list.o
4 ranlib build/liblcthw.a
5 cc -shared -o build/liblcthw.so src/lcthw/list.o
6 cc -g -O2 -Wall -Wextra -Isrc -rdynamic -DNDEBUG build/liblcthw.a
tests/list_tests.c -o tests/list_tests
7 sh ./tests/runtests.sh
8 Running unit tests:
9 ----
10 RUNNING: ./tests/list_tests
11 ALL TESTS PASSED
12 Tests run: 6
13 tests/list_tests PASS
14 $
__________________________________________________________________
Make sure 6 tests ran, that it builds without warnings or errors, and
that it's making the build/liblcthw.a and build/liblcthw.so files.
33.6 How To Improve It
Instead of breaking this, I'm going to tell you how to improve the
code:
1. You can make List_clear_destroy more efficient by using
LIST_FOREACH and doing both free calls inside one loop.
2. You can add asserts for preconditions that it isn't given a NULL
value for the List *list parameters.
3. You can add invariants that check the list's contents are always
correct, such as count is never < 0, and if count > 0 then first
isn't NULL.
4. You can add documentation to the header file in the form of
comments before each struct, function, and macro that describes
what it does.
These amount to going through the defensive programming practices I
talked about and "hardening" this code against flaws or improving
usability. Go ahead and do these things, then find as many other ways
to improve the code.
33.7 Extra Credit
1. Research double vs. single linked lists and when one is preferred
over the other.
2. Research the limitations of a double linked list. For example,
while they are efficient for inserting and deleting elements, they
are very slow for iterating over them all.
3. What operations are missing that you can imagine needing? Some
examples are copying, joining, splitting. Implement these
operations and write the unit tests for them.
[next] [prev] [prev-tail] [front] [up]
__________________________________________________________________
Please enable JavaScript to view the comments powered by Disqus.
Take An Online Video Course
You can sign up for a video course at:
http://www.udemy.com/learn-c-the-hard-way/
This course is currently being built at the same time that the book is
being built, but if you sign up now then you get early access to both
the videos and PDF of the book.
Related Books
You might want to check out these other books in the series:
1. Learn Ruby The Hard Way
2. Learn Regex The Hard Way
3. Learn SQL The Hard Way
4. Learn C The Hard Way
5. Learn Python The Hard Way
I'll be referencing other books shortly.
Copyright 2011 Zed A. Shaw. All Rights Reserved.