memory management - Invalid Conversion for Mem Allocator Method (C) -
i'm attempting finish writing memory allocator class project, not necessary homework wasn't assigned, chose project myself.
i have 2 lines marked #1 , #2, both not work , give different error messages, here details.
i'm getting following error message (for #1): incompatible types when assigning type ‘size_t *[10]’ type ‘int *’
--- or ---
(for #2) error: incompatible types when assigning type ‘size_t *[10]’ type ‘size_t **’
i can't understand why creating empty array of same type (#2) still can't "conversion". if both arrays of type size_t*, why second error message when attempting set free_array new array?
void expandarray(void) { //size_t* free_array[10]; #this how free_array declared. size_t* oldarray = free_array; int newarray[freearraysize*2]; #1 //size_t* newarray[freearraysize*2]; #2 free_array = newarray; int = 0; (i=0; i<freearraysize; i++) { free_array[i] = oldarray[i]; } (i=freearraysize; i<(freearraysize*2); i++) { free_array[i] = (size_t)null; } freearraysize = freearraysize*2; }
thanks help!
your program bugged begin with. assigning free_array (which presumably global variable) point stack variable function. if solved compile issue appropriate casting operator, memory corrupted shortly after expandarray returns.
also, don't need write for-loop copy memory old array new. use memcpy() function.
this want 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 new array newbuffer = (buffer_type*)malloc(newsize*sizeof(buffer_type)); if (free_array != null) { // copy contents of old array new array. memcpy(newbuffer, free_array, oldsize*sizeof(buffer_type)); } // 0 out contents memset(newbuffer+oldsize, '\0', (newsize-oldsize)*sizeof(buffer_type)); // make free_array point new allocation freearraysize = newsize; free_array = newbuffer; free(free_array); // ok if free_array null }
i didn't know if wanted memory buffer in "bytes" or in instances of "size_t" (as original implementation suggests). declared array of type buffer_type. can change typedef make array type want. expandarray function still work since takes sizeof(buffer_type) account memory operations.
Comments
Post a Comment