Disclaimer: This is homework. I am trying to do this and do not expect or do not want anyone to do this for me. Just a few pointers (hehe) where I am wrong will be appreciated.
The homework requires me to create an int* array that contains 10 elements, and then try to insert a million ints into it. Each insert checks if the array needs to be resized, and if so, I increase its size so that it can hold one more element.
When I insert 10,000 elements, it works fine, but if I try 100,000 elements, I get the following error:
*** glibc detected *** ./set2: realloc(): invalid old size: 0x00000000024dc010 ***
This is the code I'm running. I commented on this so that it is easy to read.
void main() { //begin with a size of 10 int currentsize = 10; int* arr = malloc(currentsize * sizeof(int)); int i; //initalize with all elements set to INT_MAX for(i = 0; i < currentsize; i++) { arr[i] = INT_MAX; } // insert random elements for(i = 0; i < 100000; i++) { currentsize = add(rand() % 100,arr,currentsize); } free(arr); } /* Method resizes array if needed, and returns the new size of the array Also inserts the element into the array */ int add(int x, int* arr, int size) { //find the first available location int newSize = size; int i; for(i = 0; i < size; i++) { if (arr[i] == INT_MAX) break; } if (i >= size) { //need to realloc newSize++; arr = realloc(arr, newSize * sizeof(int) ); } arr[i] = x; return newSize; }
source share