"C/C + +" for school recruiting interview--malloc correlation in question 17th

Source: Internet
Author: User

1. malloc

(1) Prototype: extern void *malloc (unsigned int num_bytes);

Header files:#include <malloc.h> or #include <alloc.h> (Note: The contents of alloc.h and malloc.h are identical. )

Function: Allocates a memory block of length num_bytes bytes

Description

    • If the assignment succeeds, returns a pointer to the allocated memory (void *), otherwise null is returned.
    • Use the free () function to release memory blocks when memory is no longer in use.
    • malloc allocates a memory space that specifies num_bytes bytes to the system request. The return type is the void* type. Void* represents a pointer to an indeterminate type. c,c++ Specifies that the void* type can be cast to any other type of pointer .

Example:

#include <stdio.h>  #include <malloc.h>  int main ()  {      char *p;         p= (char *) malloc (+);      if (p)          printf ("Memory allocated at:%x/n", p);      else          printf ("Not Enough memory!/n");      Free (p);      return 0;  }  

(2) different points of malloc and new

  first, the return value is different:the malloc function returns the void * type, if you write: p = malloc (sizeof (int)); The program cannot compile, error: "Cannot assign void* to int * type variable". Therefore, the cast must be passed (int *).

  Second, whether you need to specify the size of the allocation: the argument for the function is sizeof (int), which indicates the size required for an integral type of data. If you write:

int* p = (int *) malloc (1);

Code can also be compiled, but in fact only allocates 1 bytes of memory space, when you put an integer inside, there will be 3 bytes homeless , and directly "live in the neighbor's house"! The result is that the contents of the original data in the back memory are all emptied.

Malloc can also achieve the effect of new [], requesting a contiguous amount of memory by specifying the size of the memory you need.

For example, to allocate 100 spaces of type int:

int* p = (int *) malloc (sizeof (int) * 100); Allocates a memory space that can be placed down to 100 integers.

  third, whether it can be initialized : Another point can not directly see the difference is that malloc just allocates memory, and can not initialize the resulting memory, so the resulting new memory, the value will be random.

In addition to the method of allocation and final release, pointers are obtained through malloc or new and are consistent on other operations.

Summarize:

The malloc () function actually looks for a space in memory for a specified size, and then assigns the first address of the space to a pointer variable, where the pointer variable can be either a single pointer or an array's first address, depending on the specifics of the parameter size in the malloc () function. The memory space allocated by malloc here is logically contiguous, and can be physically continuous or discontinuous. For our programmers, our focus is on logical continuity, because the operating system will help us arrange memory allocations, so we can use it as a continuous.

(3) malloc implementation principleLet's start by explaining what a heap corruption is. When the input exceeds the amount of pre-allocated space, it overwrites a storage area after that space, which is called the heap corruption. This is often also used as a means of hacking, because if the storage area after the space is more important data, you can use the heap corruption to modify the data, of course, the consequences are conceivable.

In VC, withReleaseWhen the schema is compiled to run the program, the heap allocation (allocation) is called malloc,If you want to allocate 10byte of space, then only 10byte space will be allocated, but withDebugmode, the heap allocation calls the _malloc_dbg,If you just allocate 10byte of space, then it will allocate more than you want 10byte, but also more than 36byte of space to store some of the thin information, the debug heap is assigned to a chain sequentially. The following is an example of debug:malloc needs to allocate more than 36byte more memory than the actual size. The final allocated memory block is as follows: _crtmemblockheader is a doubly linked list structure, which is defined as follows:
<pre name= "code" class= "CPP" >typedef struct _crtmemblockheader{struct _crtmemblockheader *pblockheadernext;// The next allocated memory block struct _crtmemblockheader *pblockheaderprev;//the last allocated memory block Char *szfilename;//allocates the memory code of the file name int nline;// The line number of the allocated memory code size_t the size of the ndatasize;//request, such as the memory type of the 32int nblockuse;//request in the instance, such as the user type long lrequest;//request ID in the instance, Each request is logged unsigned char GAP[NNOMANSLANDSIZE];//4 byte check bit} _crtmemblockheader;
The user requests the memory to have 4 bytes of check digit before and after allocating memory, which will be initialized to 0xFD. If the 8 bytes are overwritten, the assertion failure is triggered when free. The requested 32 bytes are initialized to 0xCC (as with the initialization of the stack). The system can display errors by recording this information. For example, the memory of the cross-border access request fails to assert under Debug, and the release below does not, which can cause a huge hidden danger to the program. Many of the occasional errors in release are created in this way._crtmemblockheader Total 32 bytes, plus the 32-byte and last 4-byte check bits requested by the user are 68 bytes.the final call to the system's API requests memory. For example, Windows below is HeapAlloc. If the memory allocation fails, malloc does not call New_handler as new, and it returns null directly. Free is the _crtmemblockheader of the information to do cleanup operations, checking the check bit and so on.Finally, the system API is called to free memory. For example, Windows below is HeapFree. It is possible to write a memory that is not freed when the program exits, that is, to traverse the doubly linked list and print the code line and file name.
int* p = new  int; crtmemblockheader* Phead = (crtmemblockheader*) p;phead--;if (phead && phead-> Pblockheadernext) {phead = Phead->pblockheadernext;while (phead) {void* ptr = (void*) (phead+1); if (phead->nLine!= 0) {DbgView ("datasize:%6d line:%4d file:%s", phead->ndatasize,phead->nline,phead->szfilename);} Phead = Phead->pblockheadernext;} break;} Else{dbgview ("Invalid Header_%x", Phead);} Delete p;

2. The difference between malloc, calloc and realloc:

    • C Language and memory allocation method

<1> allocation from a static storage area .
Memory is allocated at the time of program compilation , and the entire running period of the program is present. For example, global variables, static variables, and so on.
<2> creating on the stack
When executing a function, the storage units of local variables within the function can be created on the stack and are freed automatically at the end of the function execution. Stack memory allocation operations are built into the processor's instruction set and are highly efficient, but the allocated memory capacity is limited.

<3> allocated from the heap, also known as dynamic memory allocation.
When the program is running , it uses malloc or new to request any amount of memory, and the programmer is responsible for freeing the memory with free or delete. The lifetime of dynamic memory is determined by the user, and the use is very flexible, but the problem is the most.

    • C Language and memory application related functions are mainly alloca, calloc, malloc, free, realloc and so on.

<1>Alloca is to request memory from the stack, so there is no need to release.
The memory allocated by the <2>malloc is in the heap, andNo memory initializedThe content, so basically malloc after thatCall function Memset to initialize this part of the memory space.
<3>Calloc will initialize this part of the memory, set to 0.
<4>realloc changes the size of the memory requested by malloc.
The memory that is applied to <5> is eventually freed by the function free.
When the program is in the process of malloc, but no free, it will cause a memory leak. Part of the memory is not used, but because there is no free, so the system thinks that this part of memory is still in use, resulting in continuous application of memory to the system,reduces system available memory.but a memory leak simply means that when the program is running, the OS will recycle all the resources when the program exitsAs a result, proper re-starting of the procedure is sometimes a bit of a function.
"Attention"
The declarations of the three functions are:
void* malloc (unsigned size);
void* realloc (void* ptr, unsigned newsize);
void* calloc (size_t numelements, size_t sizeofelement);
Are all within the Stdlib.h library, and their return values are the addresses that are requested by the system and return NULL if the request fails.
(1) function malloc ()
Allocates a contiguous region of size bytes in the memory's dynamic store, with the parameter size being the length of the memory space to return the first address of the region.
(2) function calloc ()
Similar to malloc, the parameter sizeofelement is the unit element length of the requisition address, numelements is the number of elements, that is, a contiguous address space that requests numelements*sizeofelement byte size in memory.
(3) function realloc ()
Reassign space to a pointer that has been assigned an address.The parameter ptr is the original space address, NewSize is the re-applied address length.
Difference:
(1) The function malloc cannot initialize the allocated memory space, andfunction Calloc canIf the memory space allocated by the malloc () function has not been used, then each of the bits may be 0, whereas if this part of the memory has been allocated, there may be a variety of data left. That is to say,programs that use the malloc () function are started (the memory space has not been reassigned) to work, but the problem may occur after a period of time (memory space has been reassigned).
(2) the function calloc () will allocate the memory space in theeach bit is initialized to 0 ., that is, if you are allocating memory for an element of character type or integer type, these elements will be guaranteed to be initialized to 0, and if you are allocating memory for elements of pointer type, then these elements will usually be initialized to null pointers, and if you allocate memory for real data, those elements will be initialized to float 0.
(3) The function malloc allocates the memory space of the specified size byte to the system request. The return type is a void* type. void* represents a pointer to an indeterminate type. c,c++ Specifies that the void* type can be cast to any other type of pointer.
(4) ReAlloc can enlarge or reduce the space indicated by a given pointer,whether it's expanding or shrinking, the contents of the original memory will remain unchanged. Of course,for shrinking, the content of the part that is shrunk is lost. REalloc does not guarantee that the adjusted memory space and the original memory space remain the same memory address. Instead, the pointer returned by ReAlloc is likely to point to a new address.
(5) ReAlloc is allocating memory from the heap. When a chunk of memory is enlarged, realloc () tries to directly follow the bytes that are behind the existing data on the heapget the additional bytes, if it can meet, natural peace; if the bytes behind the data are not enough, then the problem comes out, so use the first free block on the heap that has enough size,the existing data is then copied to the new location., and the old block is put back on the heap. An important message of this sentence is that the data may be moved.

#include <stdio.h>  #include <malloc.h>    int main (int argc, char* argv[])   {       char *p,*q;      p = (char *) malloc (+);      Q = p;      p = (char *) realloc (p,10);      printf ("p=0x%x/n", p);      printf ("q=0x%x/n", q);            return 0;   }      Output: After realloc, the memory address is not changed              p=0x431a70              q=0x431a70    Example 2:  #include <stdio.h>  #include < malloc.h>    int main (int argc, char* argv[])   {       char *p,*q;      p = (char *) malloc (+);      Q = p;      p = (char *) realloc (p,1000);      printf ("p=0x%x/n", p);      printf ("q=0x%x/n", q);            return 0;   }      Output: Memory address changed after ReAlloc              p=0x351c0              q=0x431a70  

Reference blog:

6140979

"C/C + +" for school recruiting interview--malloc correlation in question 17th

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.