Štístko
Štístko

Reputation: 180

Free a part of malloc

Is there any way to free some part of memory you created by using malloc();

Suppose I have this:

int *temp;

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

free will release all 20 byte of memory but suppose I only need 10 bytes. Can I free the first 10 bytes and save indexes? So the first index with allocated value will be temp[10].

Upvotes: 3

Views: 172

Answers (2)

Jabberwocky
Jabberwocky

Reputation: 50831

This demonstrates what you can do, but the index of the first value of the reallocated part will necessarily be 0 and not 5:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
  int* temp = malloc(10 * sizeof(int));

  // fill with values from 0 to 9
  for (int i = 0; i < 10; i++)
    temp[i] = i;

  // free first 5 ints    
  memmove(temp, &temp[5], 5 * sizeof(int));
  temp = realloc(temp, 5 * sizeof(int));

  // display the remaining 5 values of new temp
  for (int i = 0; i < 5; i++)
    printf("%d\n", temp[i]);
}

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 311048

You can use the memmove function along with the function realloc.

Here is a demonstrative program.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) 
{
    size_t n = 20;

    int *p = malloc( n * sizeof( int ) );

    for ( size_t i = 0; i < n; i++ ) p[i] = i;

    for ( size_t i = 0; i < n; i++ ) printf( "%d ", p[i] );
    putchar( '\n' );

    memmove( p, p + n / 2, n / 2 * sizeof( int ) );

    for ( size_t i = 0; i < n; i++ ) printf( "%d ", p[i] );
    putchar( '\n' );

    int *tmp = realloc( p, n / 2 * sizeof( int ) );

    if ( tmp != NULL ) 
    {
        p = tmp;
        n /= 2;
    }       

    for ( size_t i = 0; i < n; i++ ) printf( "%d ", p[i] );
    putchar( '\n' );

    free( p );

    return 0;
}

Its output is

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 
10 11 12 13 14 15 16 17 18 19 10 11 12 13 14 15 16 17 18 19 
10 11 12 13 14 15 16 17 18 19 

Upvotes: 3

Related Questions