Can realloc squeeze my array on the left side (C only)?

I want to move a large chunk of the data that I have in my memory. Unfortunately, this data is saved as an array, and I cannot change this. I cannot use circular arrays because the same memory is also used by several fortran methods that I do not want to modify. In addition to this, arrays are very often available between traffic. 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 say that my compiler removes the data on the left side of the shrinking array, my data will creep through memory, but I would not need to copy it. 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 end up with a pointer to array+1 , and 4 bytes on the left are freed. I played with free() and malloc() , but that didn’t work ... I know that realloc can also cause memcpy to be called, but not every time! It could be faster, right?

+4
source share
2 answers

Not. Unable to return the bottom of the allocated memory. Also, your source code is incorrect because you are copying undefined 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 indefinite.

+5
source

Why don't you just copy items 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 as you did, but without moving

 #define NELEMS 5 memmove(array, array + 1, (NELEMS - 1) * sizeof *array); array[NELEMS - 1] = 0; 
+3
source

All Articles