【问题标题】:Free a part of malloc释放一部分 malloc
【发布时间】:2020-03-08 06:14:46
【问题描述】:

有什么方法可以释放你使用 malloc() 创建的部分内存;

假设我有这个:

int *temp;

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

free 将释放所有 20 字节的内存,但假设我只需要 10 字节。我可以释放前 10 个字节并保存索引吗?所以第一个分配值的索引是 temp[10]。

【问题讨论】:

  • 不,你不能这样做。但是您可以使用realloc,这与您要求的不太一样。
  • 您首先必须将数据从上部移动到下部,但您不能拥有第一个索引为temp[10] 的数组。数据将从temp[0] 替换。

标签: c memory-management malloc realloc memmove


【解决方案1】:

您可以将memmove 函数与realloc 函数一起使用。

这是一个演示程序。

#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 

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2023-01-21
      • 2021-08-29
      • 2012-02-07
      • 1970-01-01
      • 2015-07-22
      • 1970-01-01
      • 2021-06-15
      • 1970-01-01
      • 2021-04-28
      相关资源
      最近更新 更多