Apsaradb for memory allocation (7.8)

Source: Internet
Author: User

Iso c specifies three functions for memory allocation:

  1. Malloc, Which allocates a specified number of bytes of memory. The initial value of the memory is indeterminate.

  2. Calloc, Which allocates space for a specified number of objects of a specified size. The space is initialized to all 0 bits.

  3. Realloc, Which increases or decreases the size of a previusly allocated area. when the size increases, it may involve moving the previusly allocated area somewhere else, to provide the additional room at the end. also, when the size increases, the initial value of the space between the old contents and the end of the new area is indeterminate.

# Include

  void *malloc(size_t size); 
  void *calloc(size_t nobj, size_t size); 
  void *realloc(void *ptr, size_t newsize);

All three return: non-null pointer if OK,NullOn Error

Void free (void * PTR );

 

The pointer returned by the three allocation functions is guaranteed to be suitably aligned so that it can be used for any data object. For example, if the most restrictive alignment requirement on a particle system requires thatDoubleS must start at memory locations that are multiples of 8, then all pointers returned by these three functions wocould be so aligned.

Because the threeAllocFunctions return a genericVoid *Pointer, if we# Include(To obtain the function prototypes), we do not explicitly have to cast the pointer returned by these functions when we assign it to a pointer of a different type.

The FunctionFreeCauses the space pointed to by PTR to be deallocated. This freed space is usually put into a pool of available memory and can be allocated in a later call to one of the threeAllocFunctions.

TheReallocFunction lets us increase or decrease the size of a previusly allocated area. (the most common usage is to increase an area .) for example, if we allocate room for 512 elements in an array that we fill in at runtime but find that we need room for more than 512 elements, we can callRealloc. If there is room beyond the end of the existing region for the requested space, thenReallocDoesn't have to move anything; it simply allocates the additional area at the end and returns the same pointer that we passed it. but if there isn't room at the end of the existing region,ReallocAllocates another area that is large enough, copies the existing 512-element array to the new area, frees the old area, and returns the pointer to the new area. because the area may move, we shouldn't have any pointers into this area. exercise 4.16 shows the useReallocWithGetcwdTo handle any length pathname. Figure 17.36 shows an example that usesReallocTo avoid arrays with fixed, compile-time sizes.

Note that the final argumentReallocIs the new size of the region, not the difference between the old and new sizes. as a special case, if PTR is a null pointer,ReallocBehaves likeMallocAnd allocates a region of the specified newsize.

Older versions of these routines allowed usReallocA block that we hadFreeD since the last callMalloc,Realloc, OrCalloc. This trick dates back to version 7 and exploited the search strategyMallocTo perform storage compaction. Solaris still supports this feature, but your other platforms do not. This feature is deprecated and shocould not be used.

The allocation routines are usually implemented withSbrk(2) system call. This system call expands (or contracts) the heap of the process. (Refer to figure 7.6.) A sample ImplementationMallocAndFreeIs given in section 8.7 of kernighan and Ritchie [1988].

AlthoughSbrkCan expand or contract the memory of a process, most versionsMallocAndFreeNever decrease their memory size. The space that we free is available for a later allocation, but the freed space is not usually returned to the kernel; that space is kept inMallocPool.

It is important to realize that most implementations allocate a little more space than is requested and use the additional space for record keepingthe size of the allocated block, a pointer to the next allocated block, and the like. this means that writing past the end of an allocated area cocould overwrite this record-keeping information in a later block. these types of errors are often catastrophic, but difficult to find, because the error may not show up until much later. also, it is possible to overwrite this record keeping by writing before the start of the allocated area.

Writing past the end or before the beginning of a dynamically-allocated buffer can reset upt more than internal record-keeping information. the memory before and after a dynamically-allocated buffer can potentially be used for other dynamically-allocated objects. these objects can be unrelated to the code corrupting them, making it even more difficult to find the source of the uption.

Other possible errors that can be fatal are freeing a block that was already freed and callingFreeWith a pointer that was not obtained from one of the threeAllocFunctions. If a process CILSMalloc, But forgets to callFree, Its memory usage continually increases; this is called leakage. By not callingFreeTo return unused space, the size of a process's address space slowly increases until no free space is left. During this time, performance can degrade from excess paging overhead.

Because memory allocation errors are difficult to track down, some systems provide versions of these functions that do additional error checking every time one of the threeAllocFunctions orFreeIs called. These versions of the functions are often specified by including a special library for the link editor. There are also publicly available sources that you can compile with special flags to enable additional runtime checking.

FreeBSD, Mac OS X, and Linux support additional debugging through the setting of environment variables. In addition, options can be passed to the FreeBSD library through the Symbolic Link/Etc/malloc. conf.

Alternate memory allocators

Repeated replacementsMallocAndFreeAre available. some systems already include libraries providing alternate memory allocator implementations. other systems provide only the standard Allocator, leaving it up to software developers to download alternatives, if desired. we discuss some of the alternatives here.

Libmalloc

SVR4-based systems, such as Solaris, includeLibmallocLibrary, which provides a set of interfaces matching the Iso c memory allocation functions.LibmallocLibrary schemdesMallopt, A function that allows a process to set certain variables that control the operation of the Storage Allocator. a function calledMallinfoIs also available to provide statistics on the memory allocator.

Vmalloc

VO [1996] describes a memory allocator that allows processes to allocate memory using different techniques for different regions of memory. In addition to the functions specificVmalloc, The Library also provides emulations of the iso c memory allocation functions.

Quick-fit

Historically, the standardMallocAlgorithm used either a best-fit or a first-fit memory allocation strategy. quick-fit is faster than either, but tends to use more memory. weinstock and Wulf [1988] describe the algorithm, which is based on splitting up memory into buffers of varous sizes and maintaining unused buffers on different free lists, depending on the size of the buffers. free implementationsMallocAndFreeBased on quick-fit are readily available from several FTP sites.

AllocaFunction

One additional function is also worth mentioning. The functionAllocaHas the same calling sequenceMalloc; However, instead of allocating memory from the heap, the memory is allocated from the stack frame of the current function. the advantage is that we don't have to free the space; it goes away automatically when the function returns. theAllocaFunction increases the size of the stack frame. The disadvantage is that some systems can't supportAlloca, If it's impossible to increase the size of the stack frame after the function has been called. Nevertheless, software packages use it, and implementations exist for a wide variety of systems.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.