释放malloc分配的一部分空间

3

有没有办法通过使用malloc()来释放一部分内存?

假设我有这样的代码:

int *temp;

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

free会释放所有20字节的内存,但是假设我只需要10字节。我能否释放前10个字节并保存索引?这样第一个具有已分配值的索引将是temp[10]。


4
不,您不能这样做。但是您可以使用 realloc 函数,这与您要求的并不完全相同。 - Jabberwocky
1
你首先需要将数据从上部移动到下部,但是你不能使用第一个索引为temp[10]的数组。数据将会替换temp[0]开始的位置。 - Weather Vane
2个回答

3
您可以结合函数realloc使用memmove函数。
这里是一个演示程序。
#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;
}

它的输出是

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 

1
这展示了你可以做什么,但重新分配部分的第一个值的索引必须是0而不是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]);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接