Can realloc shrink my array on the left side (C only)?
I want to move a large chunk of data i've got in my memory. Unfortunately this data is saved as an array, and i cannot change that. I can't use circular arrays, because the same memory is also used by a couple of fortran methods i do not want to change. On top of it, the arrays are accessed very very often in between the movement. So i can do this:
int *array = (int*) malloc(sizeof(int)*5);
int *array2=NULL;
//Now i want to move my data one step to the left
array=(int*) realloc(array,6);
array2=array+1;
memmove(array,array2,5*sizeof(int));
array=(int*) realloc(array,5);
This should work fine, but it looks so wasteful ;). If i could tell my compiler to take away data开发者_运维知识库 on the left side of a shrinking array, my data would sort of creep through the memory, but i wouldn't have to do any copying. Like this:
int *array = (int*) malloc(sizeof(int)*5);
//Now i want to move my data one step to the left
array=(int*) realloc(array,6);
array=(int*) realloc_using_right_part_of_the_array(array,5);
So basically i want to finish with a pointer to array+1
, with the 4 byte left of it freed. I played around with free()
and malloc()
but it didn't work...
I'm aware that the realloc could also result in a memcpy call, but not everytime! So it could be faster, couldn't it?
No. There is no way to give back the lower part of the memory you allocated. Also, your original code is wrong, since you're copying indeterminate memory.
int *array = (int*) malloc(sizeof(int)*5);
// Fill memory:
// array - {'J', 'o', h', 'n', '\0'};
int *array2=NULL;
//Now i want to move my data one step to the left
array=(int*) realloc(array,6);
// array - {'J', 'o', h', 'n', '\0', X};
array2=array+1;
// array2 pointer to 'o of array.
memmove(array,array2,5*sizeof(int));
// This copies the indeterminate x:
// array - {'o', h', 'n', '\0', X, X}
array=(int*) realloc(array,5);
// array - {'o', h', 'n', '\0', X}
X means indeterminate.
Why don't you simply copy the elements one by one?
#define NELEMS 5
for (i = 0; i < NELEMS - 1; i++) {
array[i] = array[i + 1];
}
array[NELEMS - 1] = 0;
or, use memmove
like you've been doing, but without the relocation
#define NELEMS 5
memmove(array, array + 1, (NELEMS - 1) * sizeof *array);
array[NELEMS - 1] = 0;
精彩评论