DynamicArraySet
Posted: Sun Oct 10, 2010 4:01 pm
I mentioned it on irc, but just wanted to post here to. If it is a bug, heres a reminder! If its not, my bad!
In 1.4.6 the return value of realloc is only checked to see if it successfully allocated and ignores whether or not a new memory block is allocated.
Solution ( I hope )
In 1.4.6 the return value of realloc is only checked to see if it successfully allocated and ignores whether or not a new memory block is allocated.
Code: Select all
-----
1.4.6
bool DynamicArraySet(DynamicArray *v, unsigned int index, void* item)
{
if(v == NULL)
{
return false;
}
if(index >= v->cur_size)
{
//resize the array, making sure it is bigger than index.
unsigned int newSize = (v->cur_size * 2 > index ? v->cur_size * 2: index + 1);
void** temp = (void**)realloc(v->data, sizeof(void*) * newSize);
if(temp == NULL)
{
return false;
}
memset(v->data + v->cur_size, 0, sizeof(void*) * (newSize - v->cur_size));
v->cur_size = newSize;
}
v->data[index] = item;
return true;
}
-----
1.4.5
void DynamicArraySet(DynamicArray *v, int index, void* item)
{
if(index >= v->cur_size)
{
v->data = (void**)realloc(v->data, sizeof(void*) * v->cur_size * 2);
memset(v->data + v->cur_size, 0, sizeof(void*) * v->cur_size);
v->cur_size *= 2;
}
v->data[index] = item;
}
Code: Select all
bool DynamicArraySet(DynamicArray *v, unsigned int index, void* item)
{
// check the array is valid
if(v == NULL)
{
return false;
}
// see if the array can handle the index or whether new memory is required
if(index >= v->cur_size)
{
// double the array size (if enough) or increase the size to handle the index
unsigned int newSize = (v->cur_size * 2 > index ? v->cur_size * 2: index + 1);
// realloc memory, check return for newp (same as oldp if the old memory block could be grown (or shrunk))
v->data = (void**)realloc(v->data, sizeof(void*) * newSize);
// check no problems with the allocation
if(v->data == NULL)
{
return false;
}
// zero the data newly allocated
memset(v->data + v->cur_size, 0, sizeof(void*) * (newSize - v->cur_size));
// record the new size of the array
v->cur_size = newSize;
}
// set the array
v->data[index] = item;
// return its success
return true;
}