⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mpatrol.txt

📁 debug source code under unix platform.
💻 TXT
📖 第 1 页 / 共 5 页
字号:
without that option in order for your program to run at a reasonablespeed.5 Memory allocations********************   In the C and C++ programming languages there are generally threedifferent types of memory allocation that can be used to hold thecontents of variables.  Other programming languages such as Pascal,BASIC and FORTRAN also support some of these types of allocation,although their implementations may be slightly different.5.1 Static memory allocations=============================   The first type of memory allocation is known as a _static memoryallocation_, which corresponds to file scope variables and local staticvariables.  The addresses and sizes of these allocations are fixed atthe time of compilation(1) and so they can be placed in a fixed-sizeddata area which then corresponds to a section within the final linkedexecutable file.  Such memory allocations are called static becausethey do not vary in location or size during the lifetime of the program.   There can be many types of data sections within an executable file;the three most common are normal data, BSS data and read-only data.BSS data contains variables and arrays which are to be initialised tozero at run-time and so is treated as a special case, since the actualcontents of the section need not be stored in the executable file.Read-only data consists of constant variables and arrays whose contentsare guaranteed not to change when a program is being run.  For example,on a typical SVR4 UNIX system the following variable definitions wouldresult in them being placed in the following sections:     int a;           /* BSS data */     int b = 1;       /* normal data */     const int c = 2; /* read-only data */   In C the first example would be considered a _tentative_declaration, and if there was no subsequent definition of that variablein the current translation unit then it would become a _common_variable in the resulting object file.  When the object file getslinked with other object files, any common variables with the same namebecome one variable, or take their definition from a non-tentativedefinition of that variable.  In the former case, the variable isplaced in the BSS section.  Note that C++ has no support for tentativedeclarations.   As all static memory allocations have sizes and address offsets thatare known at compile-time and are explicitly initialised, there is verylittle that can go wrong with them.  Data can be read or written pastthe end of such variables, but that is a common problem with all memoryallocations and is generally easy to locate in that case.  On systemsthat separate read-only data from normal data, writing to a read-onlyvariable can be quickly diagnosed at run-time.   ---------- Footnotes ----------   (1) Or more accurately, at link time.5.2 Stack memory allocations============================   The second type of memory allocation is known as a _stack memoryallocation_, which corresponds to non-static local variables andcall-by-value parameter variables.  The sizes of these allocations arefixed at the time of compilation but their addresses will varydepending on when the function which defines them is called.  Theircontents are not immediately initialised, and must be explicitlyinitialised by the programmer upon entry to the function or when theybecome visible in scope.   Such memory allocations are placed in a system memory area called the_stack_, which is allocated per process(1) and generally grows down inmemory.  When a function is called, the state of the calling functionmust be preserved so that when the called function returns, the callingfunction can resume execution.  That state is stored on the stack,including all local variables and parameters.  The compiler generatescode to increase the size of the stack upon entry to a function, anddecrease the size of the stack upon exit from a function, as well assaving and restoring the values of registers.   There are a few common problems using stack memory allocations, andmost generally involve uninitialised variables, which a good compilercan usually diagnose at compile-time.  Some compilers also have optionsto initialise all local variables with a bit pattern so thatuninitialised stack variables will cause program faults at run-time.As with static memory allocations, there can be problems with readingor writing past the end of stack variables, but as their sizes arefixed these can usually easily be located.   ---------- Footnotes ----------   (1) Or per thread on some systems.5.3 Dynamic memory allocations==============================   The last type of memory allocation is known as a _dynamic memoryallocation_, which corresponds to memory allocated via `malloc()' or`operator new[]'.  The sizes, addresses and contents of such memory varyat run-time and so can cause a lot of problems when trying to diagnosea fault in a program.  These memory allocations are called dynamicmemory allocations because their location and size can vary throughoutthe lifetime of a program.   Such memory allocations are placed in a system memory area called the_heap_, which is allocated per process on some systems, but on othersmay be allocated directly from the system in scattered blocks.  Unlikememory allocated on the stack, memory allocated on the heap is notfreed when a function or scope is exited and so must be explicitlyfreed by the programmer.  The pattern of allocations and deallocationsis not guaranteed to be (and is not really expected to be) linear andso the functions that allocate memory from the heap must be able toefficiently reuse freed memory and resize existing allocated memory onrequest.  In some programming languages there is support for a _garbagecollector_, which attempts to automatically free memory that has hadall references to it removed, but this has traditionally not been verypopular for programming languages such as C and C++, and has been morewidely used in functional languages like ML(1).   Because dynamic memory allocations are performed at run-time ratherthan compile-time, they are outwith the domain of the compiler and mustbe implemented in a run-time package, usually as a set of functionswithin a linker library.  Such a package manages the heap in such a wayas to abstract its underlying structure from the programmer, providinga common interface to heap management on different systems.  However,this _malloc library_ must decide whether to implement a fast memoryallocator, a space-conserving memory allocator, or a bit of both.  Itmust also try to keep its own internal tables to a minimum so as toconserve memory, but this means that it has very little capability todiagnose errors if any occur.   In some compiler implementations there is a builtin function called`alloca()'.  This is a dynamic memory allocation function that allocatesmemory from the stack rather than the heap, and so the memory isautomatically freed when the function that called it returns.  This isa non-standard feature that is not guaranteed to be present in acompiler, and indeed may not be possible to implement on somesystems(2).  However, the mpatrol library provides a debugging versionof this function (and a few other related functions) on all systems, sothat they make use of the heap instead of the stack.   As can be seen from the above paragraphs, dynamic memory allocationsare the types of memory allocations that can cause the most problems ina program since almost nothing about them can be used by the compilerto give the programmer useful warnings about using uninitialisedvariables, using freed memory, running off the end of adynamically-allocated array, etc.  It is these types of memoryallocation problems that the mpatrol library loves to get its teethinto!   ---------- Footnotes ----------   (1) There is currently at least one garbage collection packageavailable for C and C++ (*note Related software::).   (2) Some compilers now support variable length arrays which provideroughly the same functionality.6 Operating system support**************************   Beneath every malloc library's public interface there is theunderlying operating system's memory management interface.  Thisprovides features which can be as simple as giving processes theability to allocate a new block of memory for themselves, or it canoffer advanced features such as protecting areas of memory from beingread or written.  Some embedded systems have no operating systems andhence no support for dynamic memory allocation, and so the malloclibrary must instead allocate blocks of memory from a fixed-sized array.The mpatrol library can be built to support all of the above types ofsystem, but the more features an operating system can provide it with,the more it can do.   On operating systems such as UNIX and Windows, all dynamic memoryallocation requests from a process are dealt with by using a featurecalled _virtual memory_.  This means that a process cannot performillegal requests without them being denied, which protects the otherrunning processes and the operating system from being affected by sucherrors.  However, on AmigaOS and Netware platforms there is no virtualmemory support and so all processes effectively share the same addressspace as the operating system and any other running processes.  Thismeans that one process can accidentally write into the data structuresof another process, usually causing the other process to fail and bringdown the system.  In addition, a process which allocates a lot of memorywill result in there being less available memory for other runningprocesses, and in extreme cases the operating system itself.6.1 Virtual memory==================   _Virtual memory_ is an operating system feature that was originallyused to provide large usable address spaces for every process onmachines that had very little physical memory.  It is used by anoperating system to fool(1) a running process into believing that it canallocate a vast amount of memory for its own purposes, although whetherit is allowed to or not depends on the operating system and thepermissions of the individual user.   Virtual memory works by translating a virtual address (which theprocess uses) into a physical address (which the operating systemuses).  It is generally implemented via a piece of hardware called a_memory management unit_, or MMU.  The MMU's primary job is totranslate any virtual addresses that are referred to by machineinstructions into physical addresses by looking up a table which isbuilt by the operating system.  This table contains mappings to andfrom _pages_(2) rather than bytes since it would otherwise be veryinefficient to handle mappings between individual bytes.  As a result,every virtual memory operation operates on pages, which are indivisibleand are always aligned to the system page size.   Even though each process can now see a huge address space, whathappens when it attempts to allocate more pages than actuallyphysically exist, or allocate an additional page of memory when all ofthe physical pages are in use by it and other processes?  This problemis solved by the operating system temporarily saving one or more of theleast-used pages (which might not necessarily belong that that process)to a special place in the file system called a _swap file_, and mappingthe new pages to the physical addresses where the old pages onceresided.  The old pages which have been _swapped out_ are no longercurrently accessible, but their location in the swap file is noted inthe translation table.   However, if one of the pages that has been swapped out is accessedagain, a _page fault_ occurs at the instruction which referred to theaddress and the operating system catches this and reloads the page fromthe swap file, possibly having to swap out another page to make spacefor the new one.  If this occurs too often then the operating systemcan slow down, having to constantly swap in and swap out the same pagesover and over again.  Such a problem is called _thrashing_ and can onlyreally be overcome by using less virtual memory or buying more physicalmemory.   It is also possible to take advantage of the virtual memory system'sinteraction between physical memory and the file system in programcode, since mapping an existing file to memory means that the usualfile I/O operations can be replaced with memory read and writeoperations.  The operating system will work out the optimum way to readand write any buffers and it means that only one copy of the fileexists in both physical memory and the file system.  Note that this ishow _shared libraries_(3) on UNIX platforms are generally implemented,with each individual process that uses the shared library having itmapped to somewhere in its address space.   Another major feature of virtual memory is its ability to readprotect and write protect individual pages of process memory.  Thismeans that the operating system can control access to different partsof the address space for each process, and also means that a processcan read and/or write protect an area of memory when it wants to ensurethat it won't ever read or write to it again.  If an illegal memoryaccess is detected then a _signal_ will be sent to the process, whi

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -