1. malloc () function
1.1 malloc's full name is the memory allocation, Chinese called dynamic memory allocation.
Prototype: extern void *malloc (unsigned int num_bytes);
Description: Allocates a block of memory with a length of num_bytes bytes. If the assignment succeeds, it returns a pointer to the allocated memory, and the allocation fails to return null pointers. When memory is no longer in use, you should use the free () function to release the memory block.
1.2 void *malloc (int size);
Description: malloc allocates the memory space for the specified size byte to the system request, the return type is the void* type. Void* represents a pointer to an indeterminate type. C,c++ stipulates that the void* type can be cast to any other type of pointer.
Note: void* represents a pointer to an indeterminate type, or, more specifically, the application of memory space without knowing what type of data the user is storing in this space (for example, char or int or ...). )
1.3 Free
void free (void *firstbyte): The function is to return the space previously allocated by malloc to the program or the operating system, that is, to release the memory and let it regain its freedom.
1.4 Points to note
1 After you have applied for the memory space, you must check whether the assignment is successful.
2 When you do not need to use the memory of the application, remember to release, after the release should point to the memory pointer to null, to prevent the program behind accidentally use it.
3 The two functions should be paired. If the application is not released after the memory leak, if no reason to release that is nothing to do. Release only once, if released two times and more than two times will be error (free null pointer exception, free NULL pointer is also equal to nothing to do, so the release of the null pointer to release how many times there is no problem).
4 Although the type of the malloc () function is (void *), any type of pointer can be converted to (void *), but it is preferable to force the type conversion in front of it, as this can evade some of the compiler's checks.
1.5 malloc () Where did you get the memory space?
The answer is to get space from the heap. That is, the function returns a pointer to a piece of memory inside the heap. There is a linked list in the operating system that records the free memory address. When the operating system receives the application, it traverses the list, then looks for the first heap node that is larger than the requested space, and then deletes the node from the Free node list and assigns the node space to the program.
2. New operator
In 2.1 C + +, the array or individual objects are dynamically created and freed with new and delete.
When you create an object dynamically, you simply specify its data type without having to name the object, and the new expression returns a pointer to the newly created object, which we can access through the pointer.
int *pi=new int;
This new expression creates an integer object in the heap area, returns the address of the object, and initializes the pointer pi with that address.
2.2 Initialization of dynamically created objects
Dynamically created objects can be initialized in the form of initialization variables.
int *pi=new int (100); The object pointed to by the pointer Pi is initialized to 100
String *ps=new string (9 ');//*ps to "9999999999"
If no display initialization is provided, the class type is initialized with the default constructor of the class, and objects of the built-in type are not initialized.
You can also initialize values for dynamically created objects:
int *pi=new int ();//initialized to 0
int *pi=new Int;//pi point to an int without initialization
String *ps=new string ()//is initialized to an empty string (it is not necessary to initialize the value of its object for the class type that provides the default constructor)
2.3 Undo dynamically created objects
The delete expression frees the address space that the pointer points to.
Delete pi;/free a single object
Delete []pi;//release array
If the pointer does not point to a memory address that is assigned by new, it is illegal to use delete.
2.4 Reset the value of the pointer after the delete
Delete p; After executing the statement, p becomes an indeterminate pointer, and on many machines, although the P value is not clearly defined, it still holds the address of the object it referred to before, and the memory that P points to is released, so p is no longer valid. At this point, the pointer becomes a dangling pointer (the dangling pointer points to the memory that once held the object, but the object no longer exists). Dangling pointers often cause program errors and are difficult to detect.
Once you have deleted the object that the pointer refers to, set the pointer to 0 immediately, which makes it very clear that the pointer no longer points to any object. (0 value pointer: int *ip=0;)
2.5 Differentiating 0-valued pointers and null pointers
A 0-value pointer, a pointer to a value of 0, can be any type of pointer, can be a generic variant type void* can be a char*,int*, and so on.
Null pointer, in fact, the null pointer is just a programming concept, such as a container may be empty and non-null two basic states, and in the Non-empty may store a value is 0, so the null pointer is the human thought that the pointer does not provide any address messages.
2.6 When the new assignment fails, what does it return?
1993 years ago, C + + had been asking operator new to return 0 when memory allocation failed, and now it is asking operator new to throw Std::bad_alloc exceptions. Many C + + programs are written before the compiler starts to support the new specification. The C + + Standards Committee does not want to discard the code that has followed the return 0 specification, so they provide a different form of operator new (and operator new[]) to continue to provide the return 0 function. These forms are referred to as "no throws" because they do not use a throw, but instead take a Nothrow object using the entry point of new:
Class Widget {...};
Widget *pw1 = new widget;//allocation failure thrown Std::bad_alloc
if (PW1 = = 0) ...//this check must fail.
Widget *pw2 = new (nothrow) widget; If the allocation fails to return 0
if (pw2 = 0) ...//This check may be successful
3. The difference between malloc and new
3.1 New Returns a pointer of the specified type and can automatically calculate the required size.
Like what:
1 int *p;
p = new int; The return type is the int* type (integer pointer) and the allocation size is sizeof (int);
Or:
Int* Parr;
Parr = new int [100]; The return type is the int* type (integer pointer), and the allocation size is sizeof (int) * 100;
2) and malloc must be counted by us, and will be forcibly converted to the actual type of pointer upon return.
int* p;
p = (int *) malloc (sizeof (int) *128);//Allocate 128 (can replace the numeric value according to actual needs) integral storage unit, and store the first address of these 128 consecutive integer storage units in the pointer variable p
Double *pd= (double *) malloc (sizeof (double) *12)//Assign 12 double storage units and store the first address in the pointer variable PD
3.2 malloc just allocates the memory and cannot initialize the resulting memory, so a new memory is obtained, and the value will be random.
In addition to allocating and final release methods, the pointer is obtained through malloc or new, consistent in other operations.
4. Why do you have to new/delete with Malloc/free?
1 malloc and free are the standard library functions of the c++/c language, New/delete is the operator of C + +. Both can be used to request dynamic memory and free memory.
2 for non-internal data types of objects, optical maloc/free can not meet the requirements of dynamic objects. Objects are created with the constructor automatically executed, and the destructor is automatically executed before the object dies. Because Malloc/free is a library function and not an operator, it is not possible to impose the task of executing constructors and destructors on Malloc/free without the compiler controlling permissions.
The C + + language therefore requires a new operator to complete dynamic memory allocation and initialization, as well as an operator delete that cleans and frees up memory work. Note that New/delete is not a library function.
We do not attempt to use Malloc/free to complete the memory management of dynamic objects, we should use New/delete. Because "objects" of intrinsic data types do not have a process of structuring and destructors, Malloc/free and new/delete are equivalent to them.
3 Since the function of New/delete completely covers the Malloc/free, why does C + + not eliminate 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 release "dynamic object created by new" with free, the object may cause a program error because it cannot perform a destructor. If you use Delete to release "malloc requested dynamic memory", the result can also cause a program error, but the program's readability is poor. So new/delete have to be paired, and so is malloc/free.