dynamic memory function

dynamic memory function

1.  malloc and free

 

Malloc: Apply for a contiguous free space from memory.

Void*malloc(size_t size)// If the parameter size is 0 , the standard of the function is undefined

Free : Release the requested dynamic memory space.

#include "stdio.h"

#include "windows.h"

intmain  ()

{

int  num = 0;

scanf_s("%d", &num);

int arr[] = { 0 };

int *ptr = NULL;

ptr = ( int  *)malloc(num* sizeof ( int )); // Open up a space , if the open space is successful, it will point to

that space ;

if (NULL != ptr)

{

int i = 0;

for (i = 0; i < num; i++)

{

*(ptr + i) = 0;

}

}

printf("%p\n", ptr);

    free(ptr); // release the dynamic memory pointed to by ptr, the space has been returned to the computer

printf("%p\n", ptr);

ptr = NULL ; //The memory pointed to by ptr is invalid , that is, it is equivalent to failure to open up space, then the NULL pointer is returned, so the return value of malloc must be checked

system("pause");

return 0;

 

}

 

It can be seen from the running results that the address pointed to by ptr is the same before and after the release, but it becomes invalid after the release.

 

2.  calloc function

 

Void *calloc(size_t num,size_t size)

Create a space for num elements of size size , initializing size bytes to 0.

#include "stdio.h"

#include "windows.h"

intmain  ()

{

int  *ptr = ( int  *)calloc(10, sizeof ( int )); // open up a space

if (NULL != ptr)

{

}

printf("%p\n", ptr);

    free(ptr); // release the dynamic memory pointed to by ptr, the space has been returned to the computer

printf("%p\n", ptr);

ptr = NULL ; //The memory pointed to by ptr is invalid

system("pause");

return 0;

 

}

 

The functions of Calloc and malloc are basically the same, but each byte in the allocated space is initialized to 0 before returning the address .

 

3.  Realloc function

 

Realloc: The size of dynamically allocated memory can be adjusted

Void *realloc (void *ptr ,size_t size)

include "stdio.h"

#include "windows.h"

intmain  ()

{

int  *ptr = malloc(100); //Create a space

if (NULL != ptr)

{

}

else

{

exit(EXIT_FAILURE);

}

int *p = NULL;

ptr = realloc(ptr, 1000); //Extend the memory space to be applied by 1000; but there may be memory leaks

if (NULL != ptr)

{

p = ptr;

 

}

free(p); // release the dynamic memory pointed to by ptr, the space has been returned to the computer

    system("pause");

return 0;

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326521686&siteId=291194637