1. ## Quick realloc question

When using realloc to resize an array of say six ints to one of five ints, is it the sixth int "array[5]" that gets junked or is there no protocol?

Matt

2. K&R book says if object is smaller, it gets truncated. If larger, the extra space is uninitialized. If realloc returns NULL, then nothing happened (fail). So basically, it handles the size change, leaving the rest up to you. Hope that helps.

-Joe

3. Thanks. When I came to code the problem that had provoked the question, I actually found it wasn't an issue.

None of the online man pages say what happens when you realloc down to a smaller sized piece of memory. I didn't think it was that trivial...

4. I hope you're not doing
p = realloc( p, newsize );
even if you are shrinking the memory.

5. *coughs nervously* I might be...

... if I were, what should I do instead?

(Also , if I used that old line "it seems to work" - what would be a sign that it actually wasn't?)

Matt

6. ## Context

Code:
```void update(int deleteme, int array[], int size)
{
int i,j=0;
int *temp;
temp=array;
while(array[j]!=deleteme)
j++;
array=realloc(array,sizeof(int)*(size-1));
for(i=0;i<size;i++){
if(i<j)
array[i]=temp[i];
else
array[i]=temp[i+1];
}
free(temp);
return;
}```

> temp=array;
This is not a copy of the whole array, merely just a copy of the pointer to it. Which means you're likely to either free something which isn't even allocated, or free your real array.

I would go with something like this (untested)
Code:
```for ( i = 0 ; i < size ; i++ ) {
if ( array[i] == deleteme ) break;
}
if ( i != size ) {
void *temp;
// move everything else down one index
memmove( &array[i], &array[i+1], (size-i-1)*sizeof(int) );
// resize the array
temp = realloc( array, sizeof(int)*(size-1));
if ( temp != NULL ) {
array = temp;
} else {
// do something else with array
}
}```

8. The thing is, I want to delete only "deleteme" and keep the rest of the array intact, but less that one element. It seems like such a simple thing to do... yet it's driving me nuts!

I've tried to kid myself that what I had worked but all the problems with the rest of my code seem to stem from this bug...