Pointer new Delete

Source: Internet
Author: User

++ Is also a headache for C # programmers who are also obsessed with C ++. One of the Notes is Pointer operations and memory allocation. Unskilled program developers often encounter many problems due to improper pointer and memory operations. Skilled programmers can define pointer behavior and allocate/recycle memory independently, which improves the execution efficiency of program code.
There are two mechanisms for memory allocation/recovery. One is the malloc ()/Free () function, and the other is the new/delete operator. Malloc ()/Free () is a standard library function of C ++/C, and new/delete is a C ++ operator. They can be used to apply for dynamic memory and release memory. Since the former is a standard library function and the latter is an operator, this determines their differences in implementing memory management.
For non-Internal data objects, the use of malloc ()/Free () alone cannot meet the requirements of dynamic objects. The constructor must be automatically executed when the object is created, and the Destructor must be automatically executed before the object is extinct. Since malloc ()/Free () is a library function rather than an operator and is not controlled by the compiler, it is impossible to impose the tasks of executing constructor and destructor on malloc () /free (). Therefore, the C ++ language requires a new operator that can complete dynamic memory allocation and initialization, and a delete operator that can clean up and release memory. Note that new/delete is not a library function, but an operator reinforced in C ++.
For internal data types, malloc ()/Free () and new/delete are equivalent to the internal data types because the internal data type "object" does not have a process of construction and structure analysis. Since the new/delete function completely covers malloc ()/Free (), why does C ++ not remove malloc/free? This is because C ++ programs often call C functions, and C Programs can only use malloc/free to manage dynamic memory.
If you use free to release the "New Dynamic Object", this object may cause program errors because it cannot execute the destructor. If you use Delete to release the "dynamic memory applied by malloc", theoretically, the program will not go wrong, but the program is poorly readable. Therefore, new/delete must be paired, and the same applies to malloc/free.
In short:
1. The implementation of new/delete actually calls the malloc ()/Free () function.
2. In addition to memory allocation, new also calls the constructor, while malloc () only allocates memory.
3. In addition to memory recycle, delete also calls the destructor, while free () only recycles the memory.
4. New/delete is the operator in C ++ (instead of C), while malloc ()/Free () is a function in C ++/C.
5. malloc ()/Free () is equivalent to new/delete for internal data types; for non-Internal object types that need to be constructed and destructed, memory management can only use the new/delete operator.
6. malloc ()/Free () and new/delete should be used in pairs to prevent memory leakage.

The case below is a problem encountered by the author when using the new/delete operator. I have found that many online users have also encountered this problem. I will summarize it based on some answers on the Internet.

The following is a short program code:
Unsigned int ID;
Char * STR = new char [3];
For (ID = 100; id <110; ++ ID)
{
ITOA (ID, STR, 10 );
Printf ("% s", STR );
}
Delete [] STR;
This program can be compiled, but an error is reported during running. The reason is that the STR string we applied for is a three-character length, while the three-digit integer ID is converted to a string with four characters (3 digits, with a blank character at the end ), in fact, the content size of STR memory written to the program running is greater than the memory capacity opened by STR, which leads to an error when STR memory is recycled using Delete. Here, if the length of the STR string is opened to 4 characters, the program is correct.

The following is a problem encountered by a netizen. Because of its representativeness, it is also posted as follows:
Char * P = new char;
Int * I = new int;
P = "hi ";
Cout <* P <Endl;
* I = 123;
Delete I; // Why is the delete integer pointer correct?
Delete P; // which of the following statements about the delete string is incorrect?
A netizen gave a reasonable explanation about this problem: the cause of this error is not memory overflow but memory lost. Char * P = new char returns a byte pointer, and P = "hi" assigns a pointer to a constant string to P, this will cause the memory pointed to by P to be ignored. When the program finally uses Delete P to reclaim the memory, it does not actually recycle the part of the memory allocated by new, resulting in Memory leakage. In addition, because P points to a String constant "hi", the delete p statement is invalid.

 

 

Malloc ()/Free () is a function in C/C ++.

New/delete is the operator in C ++.

They are all used for memory allocation and recovery. Generally, new and delete are recommended in C ++, instead of malloc and free.

Malloc is a C function that can be used in C ++. New is introduced in C ++ and can be said to be an enhanced version of malloc (). For classes, using new can also automatically call the class constructor, which is very important in some cases.

New Request Heap Memory, malloc () also fromHeapApply for memory (The pointer returned by the function is a piece of memory in the heap. The operating system has a linked list that records idle memory addresses. When the operating system receives a program application, it traverses the linked list and searches for the first heap node with a larger space than the requested space, then, the node is deleted from the idle node linked list and the space of the node is allocated to the program.).

New allocates memory to the object, which can lead to the execution of constructor and the corresponding destructor (delete) will be executed before the class is destroyed.

Malloc () does not know constructor and destructor. Without these features, it is best not to use them for object creation. In C, there is no object concept, O (operator _ operator) O.

Example (in C ++ ):

String * string1 = <string *> (malloc (10 * sizeof (string); // by default, the malloc function returns the void * type, which must be forcibly converted.

String * string2 = new string [10];

The result is that string1 does point to enough space for 10 string objects, but these objects are not created in the memory (if any, their values will be random ). In other words, string1 is actually useless at all. Instead, string2 points to an array containing 10 fully constructed string objects. Each object can be safely used in any string read operation.

Free (string1 );

Delete [] string2; // If [] is not added, only one destructor is called and the memory space of a string is released!

Calling free () will release the memory directed by string1, but the string object in the memory will not call the destructor. The value of string1 is not changed, but it still points to the original place, free () only indicates that the system identifies the memory as available, but does not automatically assign null to the pointer or empty the memory. If the string object has allocated the memory as usual, all the memory will be lost (the objects in the memory still exist, but you cannot get a pointer to them, they cannot be used ). On the contrary, when you call delete on string2, each object in the array will call the Destructor before the memory is released, set the pointer to null, and clear the memory.

New = memory allocation (malloc) + initialization (call constructor)

Delete = call destructor + release memory (free)

The free memory is a memory space pointed to by the pointer, which should be empty. The deleted memory actually contains data or objects.

If you use free to release the "New Dynamic Object", this object may cause program errors because it cannot execute the destructor. If you use Delete to release the "dynamic memory applied by malloc", theoretically, the program will not go wrong, but the program is poorly readable. A good habit is to use new/delete and malloc/free pairs strictly.

For example, your objects are small and applications often dynamically add and delete objects. After running the program for a period of time, many memory fragments will be generated. Therefore, you need to write your own memory management to prevent memory fragments. You may need a large block of memory by using malloc, and then create many objects as needed. When there are no objects in the entire memory block, you can free up the large memory block. In general, malloc is used when you do not need to call the constructor, while new is used.

 

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.