Home > Back-end >  The malloc function
The malloc function

Time:09-15

Want to ask the malloc function how to use?

CodePudding user response:

See this post at https://blog.csdn.net/u012803067/article/details/60573239

CodePudding user response:

Int * p=(int *) malloc (sizeof (int) * n) n is you want to apply for a few bytes of type int

CodePudding user response:

Malloc is dynamic memory allocation function in C language,
Function prototypes: void * malloc (unsigned int num_bytes);
Parameters: num_bytes is unsigned integer, the number of bytes used to represent a distribution,
Assigning the successful return value: if returns a pointer to the allocated memory (the initial value of the storage area not sure), otherwise returns NULL pointer NULL and void * said not determine the type of a pointer, void * can point to any type of data, more clear, refers to the application memory space also don't know when the user is to use this space to store any type of data (such as char or int or... )
Function: distribution length of num_bytes bytes of memory block
Note: when the memory no longer used, should use free () function to release memory block, the function returns the pointer must be properly aligned, make its can be used for any data object, about the function of the prototype, in previous malloc returns char pointer, new ANSIC prescribed standards, the function returns pointer to void type, therefore necessary for type conversion,
Example:
# include "stdio.h"

# include "malloc. H"//malloc () function is included in the malloc. H inside

Int main (void)
{

Char * a=NULL;//declare a pointer to a char * type

A=(char *) malloc (100 * sizeof (char));//use malloc allocation of memory address, and then assigned to a

if(! A)//if the malloc fails, you can get some log

{
Perror (" malloc ");
The return - 1;
}

Sprintf (a, "% s", "HelloWorld \ n");//"HelloWorld \ n" write a point to address

Printf (" % s \ n ", a);//user input output data

Free (a);//release the memory address used

Return0;//case 2 any memory leaks?

}

(distribution type *) malloc (distribution of element number * sizeof (distribution type))
If successful, returns the first address space, the space is not initialized, if it fails, it returns 0
  • Related