Use of malloc in C)

Source: Internet
Author: User

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

Usage: # include <malloc. h>

Function: allocate memory blocks of num_bytes bytes.

Note: If the allocation is successful, the pointer pointing to the allocated memory is returned. Otherwise, the NULL pointer is returned.
When the memory is no longer used, use the free () function to release the memory block.

Example:
// Malloc. c

# Include <syslib. h> // if there is a problem with vc6.0 debugging, You 'd better change it to # include <stdio. h>.
# Include <malloc. h>
Main ()
{
Char * P;

Clrscr (); // clear screen
P = (char *) malloc (100 );
If (P)
Printf ("memory allocated at: % x", P );
Else
Printf ("not enough memory! \ N ");
Free (P );

Getchar ();
Return 0;
}

Function declaration (function prototype ):
Void * malloc (INT size );
Description: malloc applies to the system for allocating a specified size of bytes of memory. The return type is void. Void * Indicates a pointer of unknown type. C, C ++ stipulates that the void * type can be forcibly converted to any other type of pointer.
We can see from the function declaration. There are at least two differences between malloc and new: New returns a pointer of the specified type and can automatically calculate the required size. For example:
Int * P;
P = new int; // The return type is int * (integer pointer) and the allocated size is sizeof (INT );
Or:
Int * Parr;
Parr = new int [100]; // The returned type is int * (integer pointer) and the allocated size is sizeof (INT) * 100;
While malloc must be calculated by the number of bytes and forcibly converted to the actual type of pointer after the return.
Int * P;
P = (int *) malloc (sizeof (INT ));
First, the malloc function returns the void * type. If you write it as P = malloc (sizeof (INT), the program cannot be compiled and an error is returned: "You cannot assign void * to int * type variables ". Therefore, you must use (int *) to forcibly convert the data.
Second, the real parameter of the function is sizeof (INT), used to specify the size required for an integer data. If you write:
Int * P = (int *) malloc (1 );
The code can also be compiled, but in fact only one byte memory space is allocated. When you store an integer in it, three bytes will be left homeless, and you can directly "Live in the neighbor's house "! The result is that all the original data in the memory is cleared.
Malloc can also achieve the effect of new [], and apply for a continuous memory, the method is nothing more than specify the memory size you need.
For example, you want to allocate 100 int-type space:
Int * P = (int *) malloc (sizeof (INT) * 100); // allocate memory space that can be placed in the next 100 integers.
Another difference that cannot be seen directly is that malloc only allocates memory and Cannot initialize the obtained memory. Therefore, the value of a new memory will be random.
In addition to the allocation and final release methods, you can use malloc or new to obtain pointers, Which are consistent in other operations.

Add a special case to it
Char * PTR;
If (PTR = (char *) malloc (0) = NULL)
Puts ("got a null pointer ");
Else
Puts ("got a valid Pointer ");
In this case, got a valid pointer is obtained. Assign 0 to maclloc to obtain a valid pointer.


Struct hostent * HP;

// Note that sizeof (sturct hostent) is not sizeof (sturct hostent *)
// N indicates the number of sturct hostent data you need.
HP = (struct hostent *) malloc (N * sizeof (sturct hostent ));

If (! HP) // we recommend that you check whether the memory allocation is successful or not.
{
// Processing Method for memory allocation failure
}


New Delete, free malloc

First, we should know that malloc and free match each other. New and delete match each other and they cannot be confused.

Both malloc and new apply for space. However, new is a strongly-typed allocation and calls the object's constructor to initialize the object. malloc only allocates memory space but does not initialize the object.

New Adaptive type. malloc needs to be forcibly converted to new for allocation by type. malloc needs to specify the memory size. For objects, free indeed releases the object's memory, but does not call the object's destructor. Delete not only releases the object's memory, but also calls the object's destructor. Therefore, if you use free to delete the new object in the object, the memory may leak and still call free in the delete object.

Note: Although both new and malloc apply for memory, the applied locations are different. The new memory is allocated from the free store, the memory of malloc is allocated from heap (For details, refer to the memory management section of). The free store and heap are very similar and both are dynamic memory, but their locations are different, this is why the new memory cannot be released through free. However, the Microsoft compiler does not have good execution standards and may confuse free store with heap. Therefore, free can be used sometimes.

Additionally, you do not need to check for null during the delete operation.

Delete NULL; there is no problem, so

If (P)

{

Delete P;

P = NULL;

}

Not as good

Delete P;

P = NULL;

Free (null) is too much trouble.

Second explanation

Dynamic Storage Allocation
In the array chapter, we have introduced that the length of an array is pre-defined and remains unchanged throughout the program. Dynamic Array types are not allowed in C language.
For example:
Int N;
Scanf ("% d", & N );
Int A [n];
It is incorrect to use variables to indicate the length and dynamically describe the size of the array. However, in actual programming, this often happens, that is, the memory space required depends on the actual input data, and cannot be determined in advance. It is difficult to solve this problem using arrays. To solve the above problem, the C language provides some memory management functions. These memory management functions can dynamically allocate memory space as needed or recycle unused space, it provides a means to effectively use memory resources.
There are three common memory management functions:
1. Memory Allocation Function malloc
Call form:
(Type Description *) malloc (size)
Function: allocate a continuous area with a length of "size" bytes in the dynamic storage area of the memory. The Return Value of the function is the first address of the region.
The "type specifier" indicates the Data Type Used for the region.
(Type Description *) indicates to forcibly convert the returned value to this type pointer.
"Size" is an unsigned number.
For example:
PC = (char *) malloc (100 );
It indicates that a memory space of 100 bytes is allocated and forcibly converted to the character array type. The return value of the function is a pointer to the character array, and the pointer is assigned to the pointer variable PC.
2. Memory Allocation Function calloc
Calloc is also used to allocate memory space.
Call form:
(Type descriptor *) calloc (n, size)
Function: allocate n consecutive areas with a length of "size" bytes in the memory dynamic storage area. The Return Value of the function is the first address of the region.
(Type Description *) is used to force type conversion.
The difference between the calloc function and the malloc function is that n areas can be allocated at a time.
For example:
PS = (struet Stu *) calloc (2, sizeof (struct Stu ));
The sizeof (struct Stu) is the length of the stu structure. Therefore, this statement indicates that two consecutive regions are allocated according to the length of Stu, Which is forcibly converted to the stu type and the first address is assigned to the pointer variable ps.
2. Release the memory space function free
Call form:
Free (void * PTR );
Function: Release the memory space pointed to by PTR. PTR is a pointer variable of any type and points to the first address of the released area. The released zone should be the Region allocated by the malloc or calloc function.
[Example] allocate a region and input a student data.
Main ()
{
Struct Stu
{
Int num;
Char * Name;
Char sex;
Float score;
} * PS;
PS = (struct Stu *) malloc (sizeof (struct Stu ));
PS-> num = 102;
PS-> name = "Zhang Ping ";
PS-> sex = 'M ';
PS-> score = 62.5;
Printf ("number = % d \ nname = % s \ n", PS-> num, PS-> name );
Printf ("Sex = % C \ nscore = % F \ n", PS-> sex, PS-> score );
Free (PS );
}

In this example, the structure Stu is defined, and the stu type pointer variable PS is defined. Allocate a large memory area of Stu, and assign the first address to PS so that PS points to this area. Assign values to each member using the pointer variable pointing to the structure in PS, and use printf to output the value of each member. Finally, use the free function to release the memory space pointed to by PS. The entire program consists of three steps: applying for memory space, using memory space, and releasing memory space to achieve dynamic allocation of storage space.

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.