-
-
Notifications
You must be signed in to change notification settings - Fork 45
/
dmalloc.texi
3207 lines (2397 loc) · 133 KB
/
dmalloc.texi
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\input texinfo @c -*-texinfo-*-
@c %**start of header
@setfilename dmalloc.info
@settitle Dmalloc Tutorial
@headings double
@c %**end of header
@dircategory Libraries
@direntry
* Dmalloc: (dmalloc). Malloc debug library.
@end direntry
@c ----------------------------------------------------------------
@set dmalloc_version Version 5.6.5
@set dmalloc_month December
@set dmalloc_year 2020
@set dmalloc_date @value{dmalloc_month} @value{dmalloc_year}
@set dmalloc_copyright Copyright 1992 to @value{dmalloc_year} by Gray Watson.
@c ----------------------------------------------------------------
@titlepage
@headings off
@title Debug Malloc Library
@subtitle Version @value{dmalloc_version}
@subtitle @value{dmalloc_date}
@author Gray Watson
@page
This manual is licensed by Gray Watson under the Creative Commons Attribution-Share Alike 3.0 License.
Permission is granted to make and distribute verbatim copies of this manual provided this license notice and this
permission notice are preserved on all copies.
@end titlepage
@c ----------------------------------------------------------------
@c In the printed manual, we put the contents at the front. For the digital manuals it is at the end.
@iftex
@contents
@end iftex
@c --------------------------------
@node Top, License, (dir), (dir)
@top Debug Malloc Library
@everyheading @thischapter @| @thispage @| @today{}
Version @value{dmalloc_version} -- @value{dmalloc_date}
@cindex introduction
@cindex author
The debug memory allocation or @dfn{dmalloc} library has been designed as a drop in replacement for the system's
@code{malloc}, @code{realloc}, @code{calloc}, @code{free} and other memory management routines while providing powerful
debugging facilities configurable at runtime. These facilities include such things as memory-leak tracking, fence-post
write detection, file/line number reporting, and general logging of statistics.
The library is reasonably portable having been run successfully on at least the following operating systems: AIX, DGUX,
Free/Net/OpenBSD, GNU/Hurd, HPUX, Irix, Linux, OSX, NeXT, OSF/DUX, SCO, Solaris, Ultrix, Unixware, Windows, and Unicos
on a Cray T3E. It also provides support for the debugging of threaded programs. @xref{Using With Threads}.
The package includes the library, configuration scripts, debug utility application, test program, and documentation.
Online documentation as well as the full source is available at URL @uref{https://dmalloc.com/}. Details on the
library's mailing list are available there as well.
Please use the github issues URL @uref{https://github.com/j256/dmalloc/issues} if you have any problems or to request
features. Please include the version number of the library that you are using, your machine and operating system types,
and the value of the DMALLOC_OPTIONS environment variable.
Gray Watson.
@menu
* License:: Library license and copying information.
* Overview:: Description of features and how to get started.
* Programming:: How to program with the library.
* Dmalloc Program:: How to use the library's utility.
* Source Code:: Information on the source code.
* Troubleshooting:: Some solutions to common problems.
* Index of Concepts:: Index of concepts in the manual.
@end menu
@c ----------------------------------------------------------------------------
@node License, Overview, Top, Top
@chapter Library License and Copying Information
@cindex copying
@cindex license
@cindex isc license
@cindex open source license
@cindex library permissions
@cindex permissions of the library
@value{dmalloc_copyright}
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
@c ----------------------------------------------------------------------------
@node Overview, Programming, License, Top
@chapter Description of Features and How to Get Started
@cindex overview
@menu
* Installation:: How to install the library.
* Getting Started:: Getting started with the library.
* Allocation Basics:: Basic description of terms and functions.
* Features:: General features of the library.
* How It Works:: How the library checks your program.
@end menu
@c --------------------------------
@node Installation, Getting Started, Overview, Overview
@section How to Install the Library
@cindex installing the library
@cindex compiling the library
@cindex building the library
@cindex configuring the library
@cindex making the library
To configure, compile, and install the library, follow these steps carefully.
@enumerate
@item Download the latest version of the library available from @uref{https://dmalloc.com/}.
@item The release files have a @file{.tgz} file extension which means that they are a tar'd gzip'd directory of files.
You will need to ungzip and then untar the release file into your source work directory. You may have to rename the
file to @file{.tar.gz} to get some old zip programs to handle the file correctly.
@cindex settings.dist file
@item You may want to edit or at least review the settings in @file{settings.dist} to tune specific features of the
library. The @file{configure} script will copy this file to @file{settings.h} which is where you should be adding
per-architecture settings.
@cindex configure script
@cindex --disable-cxx
@cindex --enable-threads
@cindex --enable-shlib
@cindex conf.h file
@item Type @kbd{sh ./configure} to configure the library. You may want to first examine @kbd{sh ./configure --help}
output for some information about configure. You may want to use the @kbd{--disable-cxx} option if you do not want the
Makefile to build the C++ version of dmalloc. You may want to use the @kbd{--enable-threads} option to build the
threaded version of dmalloc. You may want to use the @kbd{--enable-shlib} option to build the shared versions of the
dmalloc libraries. @kbd{sh ./configure --help} lists the available options to configure. Configure should generate the
@file{Makefile} and configuration files automatically.
@item You may want to examine the @file{Makefile} and @file{conf.h} files created by configure to make sure it did its
job correctly.
@cindex settings.h file
@item You might want to tune the settings in @file{settings.h} file to tune the library to the local architecture.
This file contains relevant settings if you are using pthreads or another thread library. @xref{Using With Threads}.
The @file{configure} script created this file from the @file{settings.dist} file. Any permanent changes to these
settings should made to the @file{settings.dist} file. You then can run @file{config.status} to re-create the
@file{settings.h} file.
@cindex DMALLOC_SIZE option
@item The @code{DMALLOC_SIZE} variable gets auto-configured in @file{dmalloc.h.2} but it may not generate correct
settings for all systems. You may have to alter the definitions in this file to get things to stop complaining when you
go to compile about the size arguments to malloc routines. Comments on this please.
@item Typing @kbd{make} should be enough to build @file{libdmalloc.a}, and @file{dmalloc} program. If you figure your
problem out, please send me some notes so future users can profit from your experiences.
@cindex USE_RETURN_MACROS conf.h option
@emph{NOTE}: You may experience some errors compiling some of the @file{return.h} assembly macros which attempt to
determine the callers address for logging purposes. @xref{Portability}. You may want to first try disabling any
compiler optimization flags. If this doesn't work then you may need to disable the @samp{USE_RETURN_MACROS} variable in
the @file{settings.h} file.
@cindex ANSI-C compiler
@emph{NOTE}: The code is dependent on an ANSI-C compiler. If the configure script gives the @samp{WARNING} that you do
not have an ANSI-C compiler, you may still be able to add some sort of option to your compiler to make it ANSI. If
there such is an option, please send it to the author so it can be added to the configure script.
@item If you use threads and did not add the @kbd{--enable-threads} argument to configure, typing @kbd{make threads}
should be enough to build @file{libdmallocth.a} which is the threaded version of the library. This may or may not work
depending on the configuration scripts ability to detect your local thread functionality. Feel free to send me mail
with improvements.
See the section of the manual on threads for more information about the operation of the library with your threaded
program. @xref{Using With Threads}.
@item If you have a C++ compiler installed, the library should have automatically built @file{libdmallocxx.a} which is
the C++ version of the library. If it was not done automatically, you can build it by typing @kbd{make cxx}. You
should link this library into your C++ programs instead of @file{libdmalloc.a}. See the @file{dmallocc.cc} C++ file
which contains basic code to overload the @code{new}, @code{new[]}, @code{delete}, and @code{delete[]} C++ operators.
My apologies on the minimal C++ support. I am still living in a mostly C world. Any help improving this interface
without sacrificing portability would be appreciated.
@cindex testing the library
@cindex dmalloc_t test program
@item Typing @kbd{make light} should build and run the @file{dmalloc_t} test program through a set of light trials.
By default this will execute @file{dmalloc_t} 5 times -- each time will execute 10,000 malloc operations in a very
random manner. Anal folks can type @kbd{make heavy} to up the ante. Use @kbd{dmalloc_t --usage} for the list of all
@file{dmalloc_t} options.
@item Typing @kbd{make install} should install the @file{libdmalloc.a} library in @file{/usr/local/lib}, the
@file{dmalloc.h} include file in @file{/usr/local/include}, and the @file{dmalloc} utility in @file{/usr/local/bin}.
You may also want to type @kbd{make installth} to install the thread library into place and/or @kbd{make installcc} to
install the C++ library into place.
You may have specified a @samp{--prefix=PATH} option to configure in which case @samp{/usr/local} will have been
replaced with @samp{PATH}.
@end enumerate
See the ``Getting Started'' section to get up and running with the library. @xref{Getting Started}.
@c --------------------------------
@node Getting Started, Allocation Basics, Installation, Overview
@section Getting Started with the Library
@cindex quick start
@cindex getting started
@cindex jump start
@cindex how to begin
@cindex where to begin
@cindex beginning
This section should give you a quick idea on how to get going. Basically, you need to do the following things to make
use of the library:
@enumerate
@item Download the latest version of the library from @uref{https://dmalloc.com/}.
@cindex configure script
@item Run @kbd{./configure} to configure the library. Follow the installation instructions on how to
configure, make, and install the library (i.e. type: @kbd{make install}). @xref{Installation}.
@item Run @kbd{./make install} to install the library on your system.
@cindex automatic shutdown
@cindex shutdown, automatic
@cindex on_exit
@cindex atexit
@cindex destructor
@item You need to make sure that the library configuration and build process above was able to locate one of the
@code{on_exit} function, @code{atexit} function, or had compiler destructor support. If one of these functions or
support is available then the dmalloc library should be able to automatically shut itself down when the program exits.
This causes the memory statistics and unfreed information to be dumped to the log file. However, if your system has
none of the above, then you will need to call @code{dmalloc_shutdown} yourself before your program exits.
@cindex alias, shell
@cindex bash shell
@cindex ksh shell
@cindex zsh shell
@item To get the dmalloc utility to work you need to add an alias for dmalloc to your shell's runtime configuration
file if supported. The idea is to have the shell capture the dmalloc program's output and adjust the environment.
After you add the alias to the shell config file you need to log out and log back in to have it take effect, or you can
execute the appropriate command below on the command line directly. After you setup the alias, if you enter
@kbd{dmalloc runtime} and see any output with DMALLOC_OPTIONS in it then the alias did not take effect.
Bash, ksh, and zsh (@uref{https://zsh.org/}) users should add the following to their @file{.bashrc}, @file{.profile},
or @file{.zshrc} file respectively (notice the @kbd{-b} option for bourne shell output):
@example
function dmalloc @{ eval `command dmalloc -b $*`; @}
@end example
If your shell does not support the @code{command} function then try:
@example
function dmalloc @{ eval `\dmalloc -b $*`; @}
@end example
or use a full path to where the dmalloc binary is installed:
@example
function dmalloc @{ eval `/usr/local/bin/dmalloc -b $*`; @}
@end example
@cindex csh shell
@cindex tcsh shell
If you are still using csh or tcsh, you should add the following to your @file{.cshrc} file (notice the @kbd{-C} option
for c-shell output):
@example
alias dmalloc 'eval `\dmalloc -C \!*`'
@end example
@cindex rc shell
If you are using rc shell, you should add the following to your @file{.rcrc} file (notice the @kbd{-R} option for
rc-shell output):
@example
fn dmalloc @{eval `@{/usr/local/bin/dmalloc $*@}@}
@end example
@item Although not necessary, you may want to include @file{dmalloc.h} in your C files and recompile. This will allow
the library to report the file/line numbers of calls that generate problems. @xref{Allocation Macros}. It should be
inserted at the @emph{bottom} of your include files as to not conflict with other includes. You may want to ifdef it
as well and compile with @kbd{cc -DDMALLOC @dots{}}:
@example
/* other includes above ^^^ */
#ifdef DMALLOC
#include "dmalloc.h"
#endif
@end example
@cindex DMALLOC_FUNC_CHECK
@item Another optional task is to compile all of your source with the @file{dmalloc.h} with the
@code{DMALLOC_FUNC_CHECK} compilation flag. This will allow the library to check all of the arguments of a number of
common string and utility routines. @xref{Argument Checking}.
@example
cc -DDMALLOC -DDMALLOC_FUNC_CHECK file.c
@end example
@item Link the dmalloc library into your program. The dmalloc library should probably be placed at or near the end
of the library list.
@item Enable the debugging features by typing @kbd{dmalloc -l logfile -i 100 low} (for example). You should not see
any messages printed by the dmalloc utility (see NOTE below). This will:
@itemize @bullet
@item Set the malloc logfile name to @file{logfile} (@kbd{-l logfile}). For programs which change directories, you may
want to specify the full path to your logfile.
@item Have the library check itself every 100 iterations (@kbd{-i 100}). This controls how fast your program will run.
Larger numbers check the heap less and so it will run faster. Lower numbers will be more likely to catch memory
problems.
@item Enable a number of debug features (@kbd{low}). You can also try @kbd{runtime} for minimal checking or
@kbd{medium} or @kbd{high} for more extensive heap verification.
@item By default, the low, medium, and high values enable the @code{error-abort} token which will cause the library to
abort and usually dump core immediately upon seeing an error. @xref{Dumping Core}. You can disable this feature by
entering @kbd{dmalloc -m error-abort} (-m for minus) to remove the @code{error-abort} token and your program will just
log errors and continue.
@end itemize
@kbd{dmalloc --usage} will provide verbose usage info for the dmalloc program. @xref{Dmalloc Program}.
You may also want to install the @file{dmallocrc} file in your home directory as @file{.dmallocrc}. This allows you to
add your own combination of debug tokens. @xref{RC File}.
@emph{NOTE}: The output from the dmalloc utility should be captured by your shell. If you see a bunch of stuff which
includes the string @code{DMALLOC_OPTIONS} then the alias you should have created above is not working and he
environmental variables are not being set. Make sure you've logged out and back in to have the alias take effect.
@item Run your program, examine the logfile that should have been created by @code{dmalloc_shutdown}, and use its
information to help debug your program.
@end enumerate
@c --------------------------------
@node Allocation Basics, Features, Getting Started, Overview
@section Basic Description of Terms and Functions
@cindex allocation basics
@cindex basic allocation information
@menu
* Basic Definitions:: General memory terms and concepts.
* Malloc Functions:: Functionality supported by all malloc libs.
@end menu
@c --------------------------------
@node Basic Definitions, Malloc Functions, Allocation Basics, Allocation Basics
@subsection General Memory Terms and Concepts
@cindex basic definitions
@cindex memory definitions
Any program can be divided into 2 logical parts: text and data. Text is the actual program code in machine-readable
format and data is the information that the text operates on when it is executing. The data, in turn, can be divided
into 3 logical parts according to where it is stored: @dfn{static}, @dfn{stack}, and @dfn{heap}.
@cindex static memory
Static data is the information whose storage space is compiled into the program.
@example
/* global variables are allocated as static data */
int numbers[10];
main()
@{
@dots{}
@}
@end example
@cindex stack memory
Stack data is data allocated at runtime to hold information used inside of functions. This data is managed by the
system in the space called stack space.
@example
void foo()
@{
/* this local variable is stored on the stack */
float total;
@dots{}
@}
main()
@{
foo();
@}
@end example
@cindex heap memory
Heap data is also allocated at runtime and provides a programmer with dynamic memory capabilities.
@example
main()
@{
/* the address is stored on the stack */
char * string;
@dots{}
/*
* Allocate a string of 10 bytes on the heap. Store the
* address in string which is on the stack.
*/
string = (char *)malloc(10);
@dots{}
/* de-allocate the heap memory now that we're done with it */
(void)free(string);
@dots{}
@}
@end example
It is the heap data that is managed by this library.
Although the above is an example of how to use the malloc and free commands, it is not a good example of why using the
heap for runtime storage is useful.
Consider this: You write a program that reads a file into memory, processes it, and displays results. You would like to
handle files with arbitrary size (from 10 bytes to 1.2 megabytes and more). One problem, however, is that the entire
file must be in memory at one time to do the calculations. You don't want to have to allocate 1.2 megabytes when you
might only be reading in a 10 byte file because it is wasteful of system resources. Also, you are worried that your
program might have to handle files of more than 1.2 megabytes.
A solution: first check out the file's size and then, using the heap-allocation routines, get enough storage to read the
entire file into memory. The program will only be using the system resources necessary for the job and you will be
guaranteed that your program can handle any sized file.
@c --------------------------------
@node Malloc Functions,, Basic Definitions, Allocation Basics
@subsection Functionality Supported by All Malloc Libraries
@cindex malloc functions
All malloc libraries support 4 basic memory allocation commands. These include @dfn{malloc}, @dfn{calloc},
@dfn{realloc}, and @dfn{free}. For more information about their capabilities, check your system's manual pages -- in
unix, do a @code{man 3 malloc}.
@cindex malloc
@deftypefun void *malloc ( unsigned int @var{size} )
Usage: @code{pnt = (type *)malloc(size)}
The malloc routine is the basic memory allocation routine. It allocates an area of @code{size} bytes. It will return a
pointer to the space requested.
@end deftypefun
@deftypefun void *calloc ( unsigned int @var{number}, unsigned int @var{size} )
@cindex calloc
@cindex Allocation of zeros
@cindex zeros, allocation of
Usage: @code{pnt = (type *)calloc(number, size)}
The calloc routine allocates a certain @code{number} of items, each of @code{size} bytes, and returns a pointer to the
space. It is appropriate to pass in a @code{sizeof(type)} value as the size argument.
Also, calloc nulls the space that it returns, assuring that the memory is all zeros.
@end deftypefun
@deftypefun void *realloc ( void *@var{old_pnt}, unsigned int @var{new_size} )
@cindex realloc
Usage: @code{new_pnt = (type *)realloc(old_pnt, new_size)}
The realloc function expands or shrinks the memory allocation in @code{old_pnt} to @code{new_size} number of bytes.
Realloc copies as much of the information from @code{old_pnt} as it can into the @code{new_pnt} space it returns, up to
@code{new_size} bytes. If there is a problem allocating this memory, 0L will be returned.
If the @code{old_pnt} is 0L then realloc will do the equivalent of a @code{malloc(new_size)}. If @code{new_size} is 0
and @code{old_pnt} is not 0L, then it will do the equivalent of @code{free(old_pnt)} and will return 0L.
@end deftypefun
@deftypefun void free ( void *@var{pnt} )
@cindex free
Usage: @code{free(pnt)}
The free routine releases allocation in @code{pnt} which was returned by malloc, calloc, or realloc back to the heap.
This allows other parts of the program to re-use memory that is not needed anymore. It guarantees that the process does
not grow too big and swallow a large portion of the system resources.
@end deftypefun
@emph{WARNING}: there is a quite common myth that all of the space that is returned by malloc libraries has already been
cleared. @emph{Only} the @code{calloc} routine will zero the memory space it returns.
@c --------------------------------
@node Features, How It Works, Allocation Basics, Overview
@section General Features of the Library
@cindex features
The debugging features that are available in this debug malloc library can be divided into a couple basic
classifications:
@table @asis
@item file and line number information
@cindex file/line numbers
@cindex cpp
One of the nice things about a good debugger is its ability to provide the file and line number of an offending piece of
code. This library attempts to give this functionality with the help of @dfn{cpp}, the C preprocessor.
@xref{Allocation Macros}.
@item return-address information
@cindex return-address
To debug calls to the library from external sources (i.e. those files that could not use the allocation macros), some
facilities have been provided to supply the caller's address. This address, with the help of a debugger, can help you
locate the source of a problem. @xref{Return Address}.
@item fence-post (i.e. bounds) checking
@cindex fence-post checking
@cindex bounds checking
@cindex checking bounds
@dfn{Fence-post} memory is the area immediately above or below memory allocations. It is all too easy to write code
that accesses above or below an allocation -- especially when dealing with arrays or strings. The library can write
special values in the areas around every allocation so it will notice when these areas have been overwritten.
@xref{Fence-Post Overruns}.
@emph{NOTE}: The library cannot notice when the program @emph{reads} from these areas, only when it writes values.
Also, fence-post checking will increase the amount of memory the program allocates.
@item heap-constancy verification
@cindex constancy verification
The administration of the library is reasonably complex. If any of the heap-maintenance information is corrupted, the
program will either crash or give unpredictable results.
By enabling heap-consistency checking, the library will run through its administrative structures to make sure all is in
order. This will mean that problems will be caught faster and diagnosed better.
The drawback of this is, of course, that the library often takes quite a long time to do this. It is suitable to enable
this only during development and debugging sessions.
@emph{NOTE}: the heap checking routines cannot guarantee that the tests will not cause a segmentation-fault if the heap
administration structures are properly (or improperly if you will) overwritten. In other words, the tests will verify
that everything is okay but may not inform the user of problems in a graceful manner.
@item logging statistics
@cindex logging statistics
@cindex statistics
@cindex memory leaks
@cindex leaking memory
One of the reasons why the debug malloc library was initially developed was to track programs' memory usage --
specifically to locate @dfn{memory leaks} which are places where allocated memory is never getting freed. @xref{Memory
Leaks}.
The library has a number of logging capabilities that can track un-freed memory pointers as well as runtime memory
usage, memory transactions, administrative actions, and final statistics.
@item examining freed memory
@cindex freed memory
@cindex freed memory
Another common problem happens when a program frees a memory pointer but goes on to use it again by mistake. This can
lead to mysterious crashes and unexplained problems.
To combat this, the library can write special values into a block of memory after it has been freed. This serves two
purposes: it will make sure that the program will get garbage data if it trying to access the area again, and it will
allow the library to verify the area later for signs of overwriting.
@end table
If any of the above debugging features detect an error, the library will try to recover. If logging is enabled then an
error will be logged with as much information as possible.
The error messages that the library displays are designed to give the most information for developers. If the error
message is not understood, then it is most likely just trying to indicate that a part of the heap has been corrupted.
@cindex dump core
@cindex core dump
The library can be configured to quit immediately when an error is detected and to dump a core file or memory-image.
This can be examined with a debugger to determine the source of the problem. The library can either stop after dumping
core or continue running. @xref{Dumping Core}.
@cindex system memory problems
@cindex memory problems in system functions
@emph{NOTE}: do not be surprised if the library catches problems with your system's routines. It took me hours to
finally come to the conclusion that the localtime call, included in SunOS release 4.1, overwrites one of its fence-post
markers.
@c --------------------------------
@node How It Works,, Features, Overview
@section How the Library Checks Your Program
This is one of the newer sections of the library implying that it is incomplete. If you have any questions or issues
that you'd like to see handled here, please let me know.
The dmalloc library replaces the heap library calls normally found in your system libraries with its own versions. When
you make a call to malloc (for example), you are calling dmalloc's version of the memory allocation function. When you
allocate memory with these functions, the dmalloc library keeps track of a number of pieces of debugging information
about your pointer including: where it was allocated, exactly how much memory was requested, when the call was made,
etc.. This information can then be verified when the pointer is freed or reallocated and the details can be logged on
any errors.
Whenever you reallocate or free a memory address, the dmalloc library always performs a number of checks on the pointer
to make sure that it is valid and has not been corrupted. You can configure the library to perform additional checks
such as detected fence-post writing. The library can also be configured to overwrite memory with non-zeros (only if
calloc is not called) when it is allocated and erase the memory when the pointers are freed.
@cindex check-heap
In addition to per-pointer checks, you can configure the library to perform complete heap checks. These complete checks
verify all internal heap structures and include walking all of the known allocated pointers to verify each one in turn.
You need this level of checking to find random pointers in your program which got corrupted but that won't be freed for
a while. To turn on these checks, you will need to enable the @code{check-heap} debug token. @xref{Debug Tokens}. By
default this will cause the heap to be fully checked each and every time dmalloc is called whether it is a malloc, free,
realloc, or another dmalloc overloaded function.
Performing a full heap check can take a good bit of CPU and it may be that you will want to run it sporadically. This
can be accomplished in a couple different ways including the '-i' interval argument to the dmalloc utility.
@xref{Dmalloc Program}. This will cause the check to be run every N-th time. For instance, 'dmalloc -i 3' will cause
the heap to be checked before every 3rd call to a memory function. Values of 100 or even 1000 for high memory usage
programs are more useful than smaller ones.
@cindex LOG_ITERATION_COUNT
@cindex iteration count
@cindex memory transaction count
You can also cause the program to start doing detailed heap checking after a certain point. For instance, with 'dmalloc
-s 1000' option, you can tell the dmalloc library to enable the heap checks after the 1000th memory call. Examine the
dmalloc log file produced and use the iteration count if you have @code{LOG_ITERATION_COUNT} enabled in your
@file{settings.h} file.
The start option can also have the format @samp{file:line}. For instance, if it is set to @samp{dmalloc_t.c:126},
dmalloc will start checking the heap after it sees a dmalloc call from the @file{dmalloc_t.c} file, line number 126. If
you use @samp{dmalloc_t.c:0}, with a 0 line number, then dmalloc will start checking the heap after it sees a call from
anywhere in the @file{dmalloc_t.c} file.
@c ----------------------------------------------------------------------------
@node Programming, Dmalloc Program, Overview, Top
@chapter How to Program with the Library
@cindex programming
@menu
* Allocation Macros:: Macros providing file and line information.
* Return Address:: Getting caller address information.
* Argument Checking:: Checking of function arguments.
* Dumping Core:: Generating a core file on errors for debugging.
* Extensions:: Additional non-standard routines.
* Error Codes:: Description of the internal error numbers.
* Disabling the Library:: How to disable the library.
* Using With C++:: Using the library with C++.
* Using With a Debugger:: Using a debugger with the library.
* Using With Threads:: Using the library with a thread package.
* Using With Cygwin:: Using the library with Cygwin environment.
* Debugging A Server:: Debugging memory in a server or cgi-bin process.
* Logfile Details:: Explanation of the Logfile Output.
* Other Hints:: Various other hints that may help.
@end menu
@c --------------------------------
@node Allocation Macros, Return Address, Programming, Programming
@section Macros Providing File and Line Information
@cindex allocation macros
@cindex macros, allocation
@cindex dmalloc.h file
By including @file{dmalloc.h} in your C files, your calls to malloc, calloc, realloc, recalloc, memalign, valloc,
strdup, and free are replaced with calls to _dmalloc_malloc, _dmalloc_realloc, and _dmalloc_free with various flags.
Additionally the library replaces calls to xmalloc, xcalloc, xrealloc, xrecalloc, xmemalign, xvalloc, xstrdup, and xfree
with associated calls.
These macros use the c-preprocessor @code{__FILE__} and @code{__LINE__} macros which get replaced at compilation time
with the current file and line-number of the source code in question. The routines use this information to produce
verbose reports on memory problems.
@example
not freed: '0x38410' (22 bytes) from 'dmalloc_t.c:92'
@end example
This line from a log file shows that memory was not freed from file @file{dmalloc_t.c} line 92. @xref{Memory Leaks}.
@cindex recalloc
@cindex memalign
@cindex valloc
@cindex strdup
You may notice some non standard memory allocation functions in the above list. Recalloc is a routine like realloc that
reallocates previously allocated memory to a new size. If the new memory size is larger than the old, recalloc
initializes the new space to all zeros. This may or may not be supported natively by your operating system. Memalign
is like malloc but should insure that the returned pointer is aligned to a certain number of specified bytes.
Currently, the memalign function is not supported by the library. It defaults to returning possibly non-aligned memory
for alignment values less than a block-size. Valloc is like malloc but insures that the returned pointer will be
aligned to a page boundary. This may or may not be supported natively by your operating system but is fully supported
by the library. Strdup is a string duplicating routine which takes in a null terminated string pointer and returns an
allocated copy of the string that will need to be passed to free later to deallocate.
The X versions of the standard memory functions (xmalloc, xfree, etc.) will print out an error message to standard
error and will stop if the library is unable to allocate any additional memory. It is useful to use these routines
instead of checking everywhere in your program for allocation routines returning NULL pointers.
@emph{WARNING}: If you are including the @file{dmalloc.h} file in your sources, it is recommended that it be at the end
of your include file list because dmalloc uses macros and may try to change declarations of the malloc functions if they
come after it.
@c --------------------------------
@node Return Address, Argument Checking, Allocation Macros, Programming
@section Getting Caller Address Information
@cindex caller's address
@cindex return-address
@cindex return.h file
@cindex ra
Even though the allocation macros can provide file/line information for some of your code, there are still modules which
either you can't include @file{dmalloc.h} (such as library routines) or you just don't want to. You can still get
information about the routines that call dmalloc function from the return-address information. To accomplish this, you
must be using this library on one of the supported architecture/compilers. @xref{Portability}.
@cindex assembly hacks
The library attempts to use some assembly hacks to get the return-address or the address of the line that called the
dmalloc function. If you have unfreed memory that does not have associated file and line information, you might see the
following non-freed memory messages.
@example
not freed: '0x38410' (22 bytes) from 'ra=0xdd2c'
not freed: '0x38600' (10232 bytes) from 'ra=0x10234d'
not freed: '0x38220' (137 bytes) from 'ra=0x82cc'
@end example
@cindex ra_info.pl
With the help of a debugger, these return-addresses (or ra) can then be identified. I've provided a @file{ra_info.pl}
perl script in the @file{contrib/} directory with the dmalloc sources which seems to work well with gdb. You can also
use manual methods for gdb to find the return-address location. @xref{Translate Return Addresses}.
@c --------------------------------
@node Argument Checking, Dumping Core, Return Address, Programming
@section Checking of Function Arguments
@cindex argument checking
@cindex checking arguments
@cindex DMALLOC_FUNC_CHECK flag
One potential problem with the library and its multitude of checks and diagnoses is that they only get performed when a
dmalloc function is called. One solution this is to include @file{dmalloc.h} and compile your source code with the
@code{DMALLOC_FUNC_CHECK} flag defined and enable the @code{check-funcs} token. @xref{Debug Tokens}.
@example
cc -DDMALLOC -DDMALLOC_FUNC_CHECK file.c
@end example
@emph{NOTE}: Once you have compiled your source with DMALLOC_FUNC_CHECK enabled, you will have to recompile with it off
to disconnect the library. @xref{Disabling the Library}.
@emph{WARNING}: You should be sure to have @file{dmalloc.h} included at the end of your include file list because
dmalloc uses macros and may try to change declarations of the checked functions if they come after it.
When this is defined dmalloc will override a number of functions and will insert a routine which knows how to check its
own arguments and then call the real function. Dmalloc can check such functions as @code{bcopy}, @code{index},
@code{strcat}, and @code{strcasecmp}. For the full list see the end of @file{dmalloc.h}.
When you call @code{strlen}, for instance, dmalloc will make sure the string argument's fence-post areas have not been
overwritten, its file and line number locations are good, etc. With @code{bcopy}, dmalloc will make sure that the
destination string has enough space to store the number of bytes specified.
For all of the arguments checked, if the pointer is not in the heap then it is ignored since dmalloc does not know
anything about it.
@c --------------------------------
@node Dumping Core, Extensions, Argument Checking, Programming
@section Generating a Core File on Errors
@cindex dump core
@cindex core dump
@cindex generating core dump
@cindex error-abort
@cindex error-dump
@cindex debugger
If the @code{error-abort} debug token has been enabled, when the library detects any problems with the heap memory, it
will immediately attempt to dump a core file. @xref{Debug Tokens}. Core files are a complete copy of the program and
it's state and can be used by a debugger to see specifically what is going on when the error occurred. @xref{Using With
a Debugger}. By default, the low, medium, and high arguments to the library utility enable the @code{error-abort}
token. You can disable this feature by entering @kbd{dmalloc -m error-abort} (-m for minus) to remove the
@code{error-abort} token and your program will just log errors and continue. You can also use the @code{error-dump}
token which tries to dump core when it sees an error but still continue running. @xref{Debug Tokens}.
@cindex core file
@cindex program core
@cindex no core dump
@cindex core dump, none
@cindex missing core dump
When a program dumps core, the system writes the program and all of its memory to a file on disk usually named
@file{core}. If your program is called @file{foo} then your system may dump core as @file{foo.core}. If you are not
getting a @file{core} file, make sure that your program has not changed to a new directory meaning that it may have
written the core file in a different location. Also insure that your program has write privileges over the directory
that it is in otherwise it will not be able to dump a core file. Core dumps are often security problems since they
contain all program memory so systems often block their being produced. You will want to check your user and system's
core dump size ulimit settings.
@cindex abort
@cindex kill process
@cindex KILL_PROCESS
The library by default uses the @code{abort} function to dump core which may or may not work depending on your operating
system. If the following program does not dump core then this may be the problem. See @code{KILL_PROCESS} definition
in @file{settings.dist}.
@example
main()
@{
abort();
@}
@end example
If @code{abort} does work then you may want to try the following setting in @file{settings.dist}. This code tries to
generate a segmentation fault by dereferencing a @code{NULL} pointer.
@example
#define KILL_PROCESS @{ int *_int_p = 0L; *_int_p = 1; @}
@end example
@c --------------------------------
@node Extensions, Error Codes, Dumping Core, Programming
@section Additional Non-standard Routines
@cindex extensions
The library has a number of variables that are not a standard part of most malloc libraries:
@c --------------------------------
@cindex dmalloc_errno number
@cindex internal error number
@cindex error number
@deftypevar int dmalloc_errno
This variable stores the internal dmalloc library error number like errno does for the system calls. It can be passed
to @code{dmalloc_strerror()} (see below) to get a string version of the error. It will have a value of zero if the
library has not detected any problems.
@end deftypevar
@c --------------------------------
@cindex dmalloc_logpath variable
@cindex logfile name
@deftypevar char* dmalloc_logpath
This variable can be used to set the dmalloc log filename. The env variable @code{DMALLOC_LOGFILE} overrides this
variable.
@c --------------------------------
@end deftypevar
Additionally the library provides a number of non-standard malloc routines:
@c --------------------------------
@cindex dmalloc_shutdown function
@cindex shutdown the library
@deftypefun void dmalloc_shutdown ( void )
@cindex atexit function
@cindex on_exit function
This function shuts the library down and logs the final statistics and information especially the non-freed memory
pointers. The library has code to support auto-shutdown if your system has the @code{on_exit()} call, @code{atexit()}
call, or compiler destructor support (see @file{conf.h}). If you do not have these, then @code{dmalloc_shutdown} should
be called right before @code{exit()} or as the last function in @code{main()}.
@example
main()
@{
@dots{}
dmalloc_shutdown();
exit(0);
@}
@end example
@end deftypefun
@c --------------------------------
@cindex dmalloc_verify function
@cindex verify pointers
@cindex verify the heap
@deftypefun int dmalloc_verify ( char * @var{pnt} )
This function verifies individual memory pointers that are suspect of memory problems. To check the entire heap pass in
a NULL or 0 pointer. The routine returns DMALLOC_VERIFY_ERROR or DMALLOC_VERIFY_NOERROR.
@emph{NOTE}: @samp{dmalloc_verify()} can only check the heap with the functions that have been enabled. For example, if
fence-post checking is not enabled, @samp{dmalloc_verify()} cannot check the fence-post areas in the heap.
@end deftypefun
@c --------------------------------
@cindex dmalloc_debug function
@cindex override debug settings
@cindex set debug functionality flags
@deftypefun unsigned-int dmalloc_debug ( const unsigned int @var{flags} )
This routine sets the debug functionality flags and returns the previous flag value. It is helpful in server or cgi-bin
programs where environmental variables cannot be used. @xref{Debugging A Server}. For instance, if debugging should
never be enabled for a program, a call to @code{dmalloc_debug(0)} as the first call in @code{main()} will disable all
the memory debugging from that point on.
@emph{NOTE}: you cannot add or remove certain flags such as signal handlers since they are setup at initialization time
only.
@emph{NOTE}: you can also use @code{dmalloc_debug_setup} below.
@end deftypefun
@c --------------------------------
@cindex dmalloc_debug_current function
@cindex current debug value
@deftypefun unsigned-int dmalloc_debug_current ( void )
This routine returns the current debug functionality value value. This allows you to save a copy of the debug dmalloc
settings to be changed and then restored later.
@end deftypefun
@c --------------------------------
@cindex dmalloc_debug_setup
@cindex override debug settings
@cindex set debug functionality flags
@cindex setup debug flags
@cindex string of debug tokens
@deftypefun void dmalloc_debug_setup ( const char * @var{options_str} )
This routine sets the global debugging functionality as an option string. Normally this would be passed in in the
DMALLOC_OPTIONS environmental variable. This is here to override the env or for circumstances where modifying the
environment is not possible or does not apply such as servers or cgi-bin programs. @xref{Debugging A Server}.
Some examples:
@example
/*
* debug tokens high, threaded lock-on at 20,
* log to dmalloc.%p (pid)
*/
dmalloc_debug_setup("debug=0x4f46d03,lockon=20,log=dmalloc.%p");
/*
* turn on some debug tokens directly and log to the
* file 'logfile'