c Dynamic Request memory function:
"On the heap"
Function prototype:void *malloc (size_t size);
Function: Request a size byte of memory space, return the first address of the space, the space inside the things are random values.
Return value: Always void*, successful application, return the first address of the space, otherwise return null, so use this function must be judged on the return value.
Example: int *p = malloc (10 * 4);
The return value is not cast first. A warning is reported at compile time; second, the parameter gives a 4, just represents 32 for the machine the next integer length, portability is not good; Finally, no parameter detection, in case the allocation fails, the next operation of this pointer 1 may cause crashes. It is recommended to use the following as follows:
int *p = (int *) malloc (n * sizeof (int));
if (NULL = = p)
{
//do something or exit
}
Function prototype: vOID *calloc (size_t num, size_t size);
function function: the memory block that requests the NUM element array, the requested memory space is initialized with 0来.
Num: Number of elements
Size: Element type size
Return value: The request succeeds, returns the first address of the memory, the request fails to return NULL, when used must pay attention to monitoring whether the assignment succeeds.
Function prototype:void *realloc (void *ptr, size_t size);
Parameter description: PTR: pointer size that needs to be changed: The byte number of memory to be changed, which can be larger or smaller than the original memory space
function function: First to determine whether the current pointer to the memory block after a sufficient amount of contiguous space, if there is expansion, direct return to the source address, if there is not enough space after the point of memory, will redistribute the size of space, the original data back to the end of the new memory space, and then release the original space, Finally, returns the first address of the new allocated space.
NOTE: Returns NULL when the realloc fails;
ReAlloc failure, the original memory space does not change, will not be released and will not move, if the size is 0, the effect is equivalent to free, only the memory of the pointer is released; for the two-level pointer **a realloc, only one dimension will be released, pay attention to the memory leak when used; The pointer passed to the REALLOC must have been previously requested through malloc, Calloc, realloc, and the function is equivalent to malloc when PTR is null
void Testmemory ()
{
//Malloc
int * ptest = (int*) Malloc (Ten * sizeof (int));
DoSomething ();
if (ptest!= NULL)
{free
(ptest);
Ptest = NULL;
}
Calloc This function initializes the requested memory space to 0
int * pTest1 = (int*) calloc (the sizeof (int));
DoSomething ();
if (ptest!= NULL)
{free
(ptest);
Ptest = NULL;
}
Rellock, changing the size of the original memory space, if not changed, will open up a new memory,///
Copy the contents of the original memory,//
but will not initialize the newly opened space
int * PTest2 = (int*) malloc (A * sizeof (int));
ReAlloc (PTest2, 100*sizeof (int));
Free (PTEST2);
}
The above 3 functions must be free after using the space, otherwise it will cause memory leaks. This is a terrible thing in a big project. "Common memory leaks"
void Memoryleaks ()
{
//1, memory request forgot to release
int *ptest = (int *) malloc (10*sizeof (int));
ASSERT (NULL!= ptest);
DoSomething ();
2, the program logic is not clear, thought released, the actual memory leakage
int *ptest1 = (int *) malloc (10*sizeof (int));
int *ptest2 = (int *) malloc (10*sizeof (int));D osomething ();
PTest1 = PTest2;
Free (pTest1);
Free (PTEST2);
3, the program error operation, will heap destroy
char *ptest3 = (char *) malloc (5);
strcpy (PTest3, "Memory leaks!");
Free (PTEST3);
4. The address at the time of release and the place where the application is not identical
int *ptest4 = (int *) malloc (10*sizeof (int));
ASSERT (NULL!= pTest4);
Ptest4[0] = 0;
ptest4++;
DoSomething ();
Free (PTEST4);
}
"on the Stack"
Using _alloc (VS) or alloca (GCC) to dynamically open up memory on the stack, the memory developed on the stack is automatically maintained by the compiler, without the need for user explicit release. Use the same malloc.
These functions are functions in C language and can also be used in C + +. Let's look at C + + 's own dynamic memory-opening method: "New/delete operator"
It is simpler to use the new allocation space to appear to open than dynamic memory in C, and the return value does not need to force type conversions without having to compute the size of the required memory yourself.
void Test
{
int*
int*
int*
()
p4 = new int;
P5 = new int (3);
P6 = new Int[3];
Dynamic allocation of 4 bytes (1 int) of space a single data
//Dynamic allocation of 4 bytes (1 int) space and initialized to 3
//Dynamically allocated 12 bytes (3 int) space
delete P4;
Delete P5;
Delete[] P6
}
New and delete, new[] and delete[] must match, otherwise there may be a memory leak or even a crash problem.
void Test ()
{
//The following code does not match use, what happens? Is there a memory leak? Is it going to crash
? int* P4 = new int;
int* P5 = new int (3);
int* P6 = new int[3];int* P7 = (int*) malloc (sizeof (int));
Delete[] P4;
Delete P5;
Free (p5);
Delete P6;
Delete P7;
}
The above code is not paired, but it doesn't go wrong. But the example below is going to go wrong.
Class Test
{public
:
Test () {}
~test () {}
int i;
}
int main ()
{
Test *p1 = new test;
Delete[] P1;
Test *P2 = new TEST[10];
Delete P2;
free P2;
return 0;
}
When you use the method in the comments above to free up space, the program crashes. When the destructor in test is commented out, the program runs normally even if it is not paired. Here's a reason to explain this.
In fact, when we use new to apply for a space, the compiler first calls the operator new function, and then calls the constructor (if any) to initialize it. Among them, in the operator new function, the malloc function is called, that is, operator new is the malloc encapsulation; The compiler invokes the destructor before calling free to release the space with the delete.
Take a look at new [] and delete [], with test *P2 = new test[10], to illustrate.
As above, the compiler has a total of 44 bytes, of which the last 40 bytes are used to hold the object, and the 1 pointers returned by new[] point to the first address of the 40 bytes. The first 4 bytes hold the number of objects, its function first regardless, look at new[] is how to do:
In fact, new [] is an encapsulation of operator new[], when allocating space with new[], calls operator new[], and then within operator new[] calculates the size of the requested memory space, for example, in the example above, the 10*sizeof (test), then add 4 to the base, 44 (bytes), and operator new[] encapsulates operator new, then calls operator new. So it's clear now. The actual size of the requested space is more than 4 bytes. After operator New[] is called, the returned pointer is then offset backwards by 4 bytes, and then 10 constructors are called, followed by an initialization of the object, before returning the pointer to the 4-byte offset. Which is the pointer that the user sees.
Look at delete[], it actually encapsulates the operator delete[] and free, using delete[] to release space, first according to the incoming pointer to the space of the first 4 bytes of content (that is, the number of objects, assumed to be N), called N-time destructor (inverse, The later destructor is constructed, and then the address is passed to operator Delete[],operator Delete[] encapsulates the operator delete, which calculates the real first address of the space, and the incoming pointer is offset 4 bytes forward. Then call operator Delete.
Look at this picture and you'll be clearer:
Now you see, the top.
Test *P1 = new test; Delete[] P1;
Applied for a space, the actual size is the size of sizeof (test), but it called delete[] to release, this change but will move the pointer forward 4 bytes, so the back of free when the natural error. Similarly, test *p2 = new TEST[10]; Delete P2; Free P2; is similar. After I comment out the constructor, the compiler does not have to know how many destructors to call, and no more than 4 bytes to save the number of objects, without a constructor, so there is no error.
To sum up:
"New Role"
Call operator new to allocate space.
Invokes the constructor to initialize the object.
"Delete Action"
Call destructor Cleanup Object
Call operator Delete free space
"New[" function "
Call operator new to allocate space.
Call the N-th constructor to initialize each object separately.
"Delete[" function "
Calls the N-time destructor cleanup object.
Call operator Delete to free space.
Locate New expression: Locate the new expression by calling the constructor to initialize an object in the allocated raw memory space.
Note: Constructors in C + + are not allowed to display calls, and this is just a disguised call to the constructor.
Test *p = new TEST[10];
New (P) test;
New (p + 1) test;
//...
New (p + 9) test;
As above, the initialization of the requested space is completed, and the behavior of New/delete and new[]/delete[can be simulated by using the location of new expression, malloc and free, and the invocation of the destructor function shown. It's not written here.
"differences and connections between Malloc/free and New/delete " They are the portals of dynamic management of memory Malloc/free is a function of the C/S standard library, New/delete is the C + + operator malloc/ Free only allocates memory space/frees space dynamically. New/delete, in addition to allocating space, calls constructors and destructors for initialization and scavenging (scavenging members) Malloc/free needs to manually compute the type size and the return value void*,new/delete the size of the type, and returns a pointer to the corresponding type For objects that are not internal data types, Maloc/free cannot meet the requirements of dynamic objects. Objects are created with the constructor automatically executed, and the destructor is automatically executed before the object dies. Since Malloc/free is a library function and not an operator, it is not within the compiler's control to impose the task of executing constructors and destructors on malloc/free they all need to be paired with each other