In C, is it only possible to free an array of the first or last position?

I have an array, but I do not need its first (or last) position. So I point the new variable to the rest of the array, but I have to free the first or last position of the array. For instance:

p = read_csv_file(); q = p + 1; // I don't need the first CSV file field // Here I'd like to free only the first position of p return q; 

Otherwise, I have to memcpy the array to another variable, except for the first position, and then free the original array. Like this:

 p = read_csv_file(); q = (int*) malloc(sizeof(int) * (SOME_SIZE - 1)); memcpy(q, p+1, sizeof(int) * (SOME_SIZE - 1)); free(p); return q; 

But then I will have the overhead of copying the entire array.

Is it possible to free only one position of an array?

+4
source share
2 answers

Not. You can only free() get the full block received from calling malloc() (or one of malloc() friends), and not part of that block.

It’s best to leave the selected block as is and just use the pointer to the element in the index one, as if it were the beginning of the array (and ignore the last element).

Using memcpy works if it is really important to free two elements.

You can also move all elements from the left to one (i.e. move an element with an index of one to zero, etc.), and then call realloc() to resize the block and remove the last two elements. However, this is not a good idea, because the most likely result is that either (a) the main distribution of the heap will not actually change, and you will move and get profit, or (b) the basic distribution of the heap will be changed, and that's it will be moved a second time.

+4
source

This is what realloc(3) means. To free the first element of the array, I would suggest revising the algorithm.

+2
source

Source: https://habr.com/ru/post/1311465/


All Articles