Reputation: 2301
I'm attempting to finish up writing a memory allocator for a class project, not necessary homework as it wasn't assigned, I chose this project myself.
I have two lines marked #1 and #2, both do not work and give different error messages, here are the details.
I'm getting the following error message (for #1): incompatible types when assigning to type ‘size_t *[10]’ from type ‘int *’
--- OR ---
(for #2) error: incompatible types when assigning to type ‘size_t *[10]’ from type ‘size_t **’
I can't understand why creating an empty array of the same type (#2) still can't do the "conversion". If both arrays are of type size_t*, why do I get the second error message when attempting to set FREE_ARRAY to the new array?
void expandArray(void)
{
//size_t* FREE_ARRAY[10]; #This is how FREE_ARRAY is declared.
size_t* oldArray = FREE_ARRAY;
int newArray[freeArraySize*2]; #1
//size_t* newArray[freeArraySize*2]; #2
FREE_ARRAY = newArray;
int i = 0;
for (i=0; i<freeArraySize; i++)
{
FREE_ARRAY[i] = oldArray[i];
}
for (i=freeArraySize; i<(freeArraySize*2); i++)
{
FREE_ARRAY[i] = (size_t)NULL;
}
freeArraySize = freeArraySize*2;
}
Thanks for any help!
Upvotes: 0
Views: 107
Reputation: 104569
Your program is bugged to begin with. You are assigning FREE_ARRAY (which is presumably a global variable) to point to a stack variable from the function. Even if you solved the compile issue with an appropriate casting operator, that memory will get corrupted very shortly after expandArray returns.
Also, you don't need to write for-loop to copy the memory from the old array into the new. Just use the memcpy() function.
This is what you want to do:
typedef unsigned char BUFFER_TYPE;
BUFFER_TYPE* FREE_ARRAY = NULL;
size_t freeArraySize = 0;
size_t INITIAL_SIZE = 100;
void expandArray()
{
BUFFER_TYPE* newBuffer = NULL;
size_t newSize = 0;
size_t oldSize = 0;
if ((freeArraySize == 0) || (FREE_ARRAY == NULL))
{
newSize = INITIAL_SIZE;
}
else
{
newSize = freeArraySize * 2;
oldSize = freeArraySize;
}
// allocate the new array
newBuffer = (BUFFER_TYPE*)malloc(newSize*sizeof(BUFFER_TYPE));
if (FREE_ARRAY != NULL)
{
// copy the contents of the old array into the new array.
memcpy(newBuffer, FREE_ARRAY, oldSize*sizeof(BUFFER_TYPE));
}
// zero out the extra contents
memset(newBuffer+oldSize, '\0', (newSize-oldSize)*sizeof(BUFFER_TYPE));
// make FREE_ARRAY point to the new allocation
freeArraySize = newSize;
FREE_ARRAY = newBuffer;
free(FREE_ARRAY); // ok if FREE_ARRAY is NULL
}
I didn't know if you wanted your memory buffer to be in "bytes" or in instances of "size_t" (as your original implementation suggests). So I just declared the array to be of type BUFFER_TYPE. You can change the typedef to make the array any type you want. The expandArray function will still work since it takes sizeof(BUFFER_TYPE) into account for all memory operations.
Upvotes: 1