views:

99

answers:

2

Hi there!

I've an array, but I don't need its first (or last) position. So I point a new variable to the rest of the array, but I should free the array first/last position. 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've to memcpy the array to other variable, excluding 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'll have the overhead of copying all the array.

Is this possible to only free a single position of an array?

+4  A: 

No. You can only free() a complete block obtained from a call to malloc() (or one of malloc()'s friends), not a piece of that block.

Your best bet is probably to leave the allocated block as-is and just use a pointer to the element at index one as if it were the beginning of the array (and ignore the last element).

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

You could also shift all of the elements to the left by one (i.e., move the element at index one to index zero and so forth) and then call realloc() to resize the block and remove the last two elements. This isn't really a good idea, though, because the most likely outcome is that either (a) the underlying heap allocation won't actually be resized and you'll have moved thing around and gotten no benefit, or (b) the underlying heap allocation will be resized and everything will get moved a second time.

James McNellis
+1  A: 

That is what realloc(3) is for. For releasing the first array element I'd suggest revising the algorithm.

Nikolai N Fetissov