有没有办法通过使用malloc()来释放一部分内存?
假设我有这样的代码:
int *temp;
temp = ( int *) malloc ( 10 * sizeof(int));
free(temp);
free
会释放所有20字节的内存,但是假设我只需要10字节。我能否释放前10个字节并保存索引?这样第一个具有已分配值的索引将是temp[10]。
有没有办法通过使用malloc()来释放一部分内存?
假设我有这样的代码:
int *temp;
temp = ( int *) malloc ( 10 * sizeof(int));
free(temp);
free
会释放所有20字节的内存,但是假设我只需要10字节。我能否释放前10个字节并保存索引?这样第一个具有已分配值的索引将是temp[10]。
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
#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]);
}
realloc
函数,这与您要求的并不完全相同。 - Jabberwockytemp[10]
的数组。数据将会替换temp[0]
开始的位置。 - Weather Vane