What new size should I assign my array when using realloc if i have an array of floats and want to increase it by one cell.
What new size should I assign my array when using realloc if i have an array of floats and want to increase it by one cell.
You need to know how big your array is:
Code:int main() { float *array = NULL; int i = 0; for(i = 0; i < 10; i++) { array = (float *)realloc(array, sizeof(*array) * (i+1)); array[i] = 1; } free(array); return 0; }
Mmm, now shall I point out the subtle bug in this code or not...
>Mmm, now shall I point out the subtle bug in this code or not...
I'm guessing, how about memory leak?
Don't know what's wrong with it so.... yes please.Originally posted by Salem
Mmm, now shall I point out the subtle bug in this code or not...
You are not using 'sizeof' on a variable _type_, and more seriously, you are scribbling into RAM because your 'array' wasn't ever allocated. You only created space for the pointer that would contain the address of the memory allocated to the array.
When I change the array from float to double the sizeof(*array) returns 8 bytes.Originally posted by Sayeh
You are not using 'sizeof' on a variable _type_, and more seriously, you are scribbling into RAM because your 'array' wasn't ever allocated. You only created space for the pointer that would contain the address of the memory allocated to the array.
So, still don't know what's wrong with it.
>You are not using 'sizeof' on a variable _type_
Are you sure about that? By taking the size of a dereferenced variable, you get the size of it's type. Not only is this correct, it's recommended because you don't bind the function call too closely with the type. I'm not quite sure about C++, but this is considered a safer and more maintenance friendly method for allocating memory in C.
>Don't know what's wrong with it so.... yes please.
Code:int main() { float *array = NULL; int i = 0; for(i = 0; i < 10; i++) { array = (float *)realloc(array, sizeof(*array) * (i+1)); /* Bang! Your foot is history if realloc fails */ array[i] = 1; /* To be correct, this should be array[i] = 1.0f; */ } free(array); return 0; }
My best code is written with the delete key.
Prelude, you're right about the realloc returning a NULL pointer.
Not exactly a bug but still bad progamming. I think I should change my signature....