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
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
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
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...
I hope you're not doing
p = realloc( p, newsize );
even if you are shrinking the memory.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
*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
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; }
Yep, that's pretty bad
> 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.
Both are bad news.
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 } }
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
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...