The authoritative official explanation of malloc function
The following will summarize and organize the knowledge points for you in detail.
Summary of malloc function knowledge points
malloc function prototype
void* malloc(size_t size)
//size_t是无符号整型unsigned int
malloc function function
The C library function void *malloc(size_t size) allocates the required memory space and returns a pointer to it.
malloc isthat allocates memory space .
malloc function parameters
Use the sizeof operator to calculate the size of a variable required to apply for the corresponding memory space .
Because the memory space cannot be a negative number, the unsigned integer type size_t is returned .
Little knowledge about malloc function
After the malloc function allocates memory space, this function will return a pointer to the starting position of the memory block.
If the newly allocated memory is not initialized, it will have a random value.
If the size parameter in malloc is 0, then the allocated space will depend on the specific library implementation, which may or may not be a null pointer, but the null pointer (that is, a wild pointer) cannot be dereferenced.
The malloc function is prone to errors
The parameter in malloc is the number of bytes that need to be dynamically allocated , not the number of elements that can be stored!
When memory is dynamically allocated, character data is stored, and each element is 1 byte, so the number of bytes is exactly equal to the number of elements that need to be stored (number of characters + 1);
If integer or floating-point data is stored, the number of bytes is equal to " the number of elements to be stored * the number of bytes of one element " , code format:
type *var_name = (type*)malloc(sizeof(type)*num);
malloc function usage example
pointer itself = ( pointer type * ) malloc ( sizeof (pointer type) * number of data )
int *p = NULL;
int n = 10;
p = (int *)malloc(sizeof(int)*n);