Dynamically allocate memory in c, free up some of the memory allocated before using malloc ()

Is there a way to free some of the memory that you created using malloc ();

suppose: -

int *temp;

temp = ( int *) malloc ( 10 * sizeof(int));
free(temp);

free () will free all 20 bytes of memory, but suppose I need only 10 bytes. Can I free the last 10 bytes.

+4
source share
2 answers

You must use the standard library function realloc. As the name suggests, it redistributes the memory block. Its prototype (contained in the title stdlib.h)

 void *realloc(void *ptr, size_t size);

, ptr, size . malloc, realloc calloc. , realloc size , , , free .

realloc . , NULL, . ptr temp realloc . , malloc - malloc?

// allocate memory for 10 integers
int *arr = malloc(10 * sizeof *arr);
// check arr for NULL in case malloc fails

// save the value of arr in temp in case
// realloc fails
int *temp = arr;  

// realloc may keep the same block of memory
// and free the memory for the extra 5 elements
// or may allocate a new block for 5 elements,
// copy the first five elements from the older block to the
// newer block and then free the older block
arr = realloc(arr, 5 * sizeof *arr);
if(arr == NULL) {
    // realloc failed
    arr = temp;
}
+3

realloc, c.

C99 7.20.3.4-1: realloc:

realloc , ptr, , . , , . .

+3

Source: https://habr.com/ru/post/1536306/


All Articles