免責聲明:這是作業。我正在嘗試它,不要期望或希望任何人爲我做這件事。只是幾個指針(嘿嘿),我會錯誤的將不勝感激。realloc無效的舊尺寸
作業要求我創建一個包含10個元素的int*
數組,然後嘗試向其中插入一百萬個int。每個插入檢查數組是否需要調整大小,如果是這樣,我增加它的大小,以便它可以保存一個元素。
當我插入10,000個元素,它工作正常,但如果我嘗試100000元,我得到以下錯誤:
*** glibc detected *** ./set2: realloc(): invalid old size: 0x00000000024dc010 ***
這是我運行的代碼。我評論過它,因此它易於閱讀。
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;
}
應該添加接收'int **'不會導致此問題? – xbonez 2012-07-10 03:54:18
是的使用'int **' – Hogan 2012-07-10 03:55:43
是的,你說你不想要答案,我尊重這一點。你是對的。 – Gene 2012-07-10 03:58:36