2012-07-10 141 views
4

免责声明:这是作业。我正在尝试它,不要期望或希望任何人为我做这件事。只是几个指针(嘿嘿),我会错误的将不胜感激。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; 
} 

回答

5

的错误可能是因为你正确使用的realloc的功能add改变arr,但是这个修改后的值时丢失add回报。所以下一次拨打电话add将会收到旧的,现在不好的价值。

另外我不明白你为什么使用for循环来搜索。你知道你想添加最后一个元素,为什么搜索?只需重新分配阵列并在新插槽中插入新值即可。

顺便说一句,我很确定你的老师试图让你看到,为每个成员重新分配导致一个渐近运行时间问题。大多数realloc的实现将使用该算法进行拷贝lot。这就是为什么真正的程序将阵列大小增加因子大于1(通常为1.5或2),而不是固定的数量。

通常的习惯用法是抽象的可变尺寸阵列中的结构:

typedef struct array_s { 
    int *elts; 
    int size; 
} VARIABLE_ARRAY; 

void init(VARIABLE_ARRAY *a) 
{ 
    a->size = 10; 
    a->elts = malloc(a->size * sizeof a->elts[0]); 
    // CHECK FOR NULL RETURN FROM malloc() HERE 
} 

void ensure_size(VARIABLE_ARRAY *a, size_t size) 
{ 
    if (a->size < size) { 

    // RESET size HERE TO INCREASE BY FACTOR OF OLD SIZE 
    // size = 2 * a->size; 

    a->elts = realloc(size * sizeof a->elts[0]); 
    a->size = size; 

    // CHECK FOR NULL RETURN FROM realloc() HERE 
    } 
} 

// Set the i'th position of array a. If there wasn't 
// enough space, expand the array so there is. 
void set(VARIABLE_ARRAY *a, int i, int val) 
{ 
    ensure_size(a, i + 1); 
    a->elts[i] = val; 
} 

void test(void) 
{ 
    VARIABLE_ARRAY a; 

    init(&a); 

    for (int i = 0; i < 100000; i++) { 
    set(&a, i, rand()); 
    } 

    ... 

} 
+0

应该添加接收'int **'不会导致此问题? – xbonez 2012-07-10 03:54:18

+0

是的使用'int **' – Hogan 2012-07-10 03:55:43

+1

是的,你说你不想要答案,我尊重这一点。你是对的。 – Gene 2012-07-10 03:58:36

1

我会通过arradd()作为指针(的指针),以便它可以的add()

内进行修改
int add(int x, int** arr, int size) 
{ 
    // ... 
    *arr = realloc(*arr, newSize * sizeof(int)); 
} 

,把它....

currentsize = add(rand() % 100, &arr, currentsize); 

请注意,您的代码(和我建议的更改)没有进行任何错误检查。您应该检查mallocrealloc的返回值NULL

相关问题