Detail the use of free of function and getpagesize of function in C language

  • 2020-04-02 03:16:30
  • OfStack

C language free() function: free dynamically allocated memory space
The header file:


#include <stdlib.h>

The free() function is used to free up dynamically allocated memory space, and its prototype is:


 void free (void* ptr);

Free () frees up memory space allocated by malloc(), calloc(), and realloc() for other programs to use again.

PTR is the address of the memory space to be freed.

Free () only frees up dynamically allocated memory space, not arbitrary memory. The following is wrong:


int a[10];
// ...
free(a);

If the memory space that PTR points to is not allocated by the above three functions or has been freed, then calling free() can be unpredictable.

If PTR is NULL, free() won't do anything.

Note: free() does not change the value of the PTR variable itself, it still points to the same memory space when free() is called, but the memory is invalid and cannot be used. Therefore, it is recommended to set the value of PTR to NULL, for example:


free(ptr);
ptr = NULL;

Code example:


#include <stdlib.h>
int main ()
{
 int * buffer1, * buffer2, * buffer3;
 buffer1 = (int*) malloc (100*sizeof(int));
 buffer2 = (int*) calloc (100,sizeof(int));
 buffer3 = (int*) realloc (buffer2,500*sizeof(int));
 free (buffer1);
 free (buffer3);
 system("pause");
 return 0;
}

C getpagesize() function: gets the pagesize
The header file:


#include <unistd.h>

Definition function:


size_t getpagesize(void);

Returns the size of a page in bytes. This is the paging size of the system and may not be the same as the paging size of the hardware.

Return value: page size.

Note: on Intel x86 the return value should be 4096bytes.

sample


#include <unistd.h>
main(){
 printf("page size = %dn", getpagesize());
}


Related articles: