Page 1 of 1
krealloc
Posted: Fri Jan 02, 2004 11:45 am
by Adek336
Hi! Once when I needed krealloc() I wrote my implementation, which allocs a new block and copies memory there from the first one. This works fine but now I was thinking about rewriting it. I already use it in many places like this:
Code: Select all
char *buf, *new_buf;
uint32 new_size;
***
new_buf = krealloc(buf, new_size);
if (!new_buf) sysfail("not enough memory");
else
{
kfree(buf);
buf = new_buf
}
***
As we see, the old block gets disposed every time the memory's sufficient. If krealloc() did not alloc a new block but just increased the size of the old one, none of them would survive
Or perhaps krealloc DOES dispose the old block?
Cheers,
Adrian
Re:krealloc
Posted: Fri Jan 02, 2004 12:38 pm
by Tim
Well, a simple realloc could look like this: (or krealloc, if that's what you call it)
Code: Select all
void *realloc(void *old_block, size_t new_size)
{
void *new_block;
size_t old_size;
new_block = malloc(new_size);
if (new_block == NULL)
{
/* leave old block intact */
return NULL;
}
if (old_block == NULL)
old_size = 0;
else
old_size = __msize(old_block);
memcpy(new_block, old_block, min(old_size, new_size));
free(old_block);
return new_block;
}
You could optimise this by checking whether there is enough space just after old_block to satisfy the request. If so, you would update the size of the old_block and return. If not, you would use the code above.
I think the code I just wrote is standards-compliant. Here realloc(NULL, size) is the same as malloc(size), and realloc(block, 0) returns a zero-length but non-null block. I don't know what the wording in the standard is, but I think this behaviour conforms to it. Then again, if you're writing kmalloc/kfree/krealloc and not malloc/free/realloc, you can do what you like.
Re:krealloc
Posted: Sat Jan 03, 2004 5:17 am
by Pype.Clicker
personnally, i've seen so many broken code due to a misused realloc-stuff that i did not provide any krealloc ... and i'm not missing it so far.
Re:krealloc
Posted: Sat Jan 03, 2004 5:35 am
by BI lazy
Hehe ... my entire kmalloc library 's been buggy a big while long: I didn't do it reentrant - well, it isn't reentrant by nature, is it? and upon krealloc for a local copy of the active window in the video driver, it crapped out unfortunately - until I found out that my messaging stuff did this to the system.
Now, I 've got a quick and secure msg_alloc and msg_free set and the normal kmalloc functions.
Well ... as soon as you need to allcoate memory for growing/shrinking objects, realloc stuff comes in handy.
But as Pype says: most trouble stems from buggy allocation stuff which doesn't do its work properly.