malloc and free in the C language

Source: Internet
Author: User

The function for dynamically allocating memory in the C language is the malloc () function, and the corresponding memory-deallocation function is the function. Their function prototypes were:

void *malloc ( size_t size );// Header file is Stdlib.h or Malloc.hvoid free ( void *memblock ); 
The

parameter size is the allocated byte size (not the number of elements!). )。


The allocation of level two pointers is often confusing ... Now make a summary: the

C language to the two-level pointer to the memory allocation, the first allocation of the outer pointer memory space (hold pointer value), and then allocate the internal pointer to the memory space (holding the object value), the memory is released in order to release the internal pointer to the address space first, Finally, the address space referred to by the outermost pointer is released.


is explained under a specific program:

float** p =  (float* *) malloc (240 * sizeof (float));//Assign an address space to the outer pointer p  //and assign an address space to the inner pointer int i;for (i = 0;  i < 240; i++) {  p[i] =  (float*) malloc (1216 * sizeof ( float));}  ...... //free Memory for (i = 0; i < 240; i++) {  free (p[i]);// Frees the memory pointer to the address space}//finally releases the address space that the outer pointer refers to free (p); 


This article is from the "xinyi_xft" blog, declined reprint! malloc and free

in the

C language

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.