Trần Văn Thành
Trần Văn Thành

Reputation: 123

realloc fail even when i still have much space in main memory

#include<iostream>
#include<algorithm>
#include<malloc.h>
#include<stdlib.h>
using namespace std;

typedef struct _intExpandArray{
    int size;
    int max;
    int *base;
} intExpandArray;

void addExpandArrayElement(intExpandArray *arr, int element){
    int *p;
    if(arr->base == NULL){
        arr->base = (int* )malloc(2*sizeof(int));
        arr->size = 0;
        arr->max = 2;
        cout<<"base = " << arr->base <<endl;
    }else if(arr->size >= arr->max){
        p = (int *)realloc(arr->base, arr->max*2*sizeof(int));
        if(p != NULL){
            cout<<"reallocate successful base = " << arr->base << endl;
            arr->max *= 2;  
        }else{
            cout<<"reallocate failed base = "<< arr->base <<endl;
        }
    }
    *(arr->base + arr->size) = element;
    arr->size++;
}

/* display array */
void dispIntExpandArray(intExpandArray arr){
    int i;
    int n = arr.size;
    int *p = arr.base;
    cout<< "size = " << n << " max size = " << arr.max << endl;
    for(i = 0; i < n; i++){
        cout<<p[i]<<" ";
    }
    cout<<endl;
}

int main(){
    intExpandArray arr;
    arr.base = NULL;
    int i = 0;
    for(i = 0; i < 10; i++){
        addExpandArrayElement(&arr, i);
        //dispIntExpandArray(arr);
    }
    return 0;
}

why can't i reallocate memory ? (i still have many ram on my window operating system) when i run this code the malloc funtion work fine but the realloc funtion just work one first time and fail from second time on so i get one "reallocate successful base = ..." message and 6 "reallocate fail base = ..." message

Upvotes: 2

Views: 49

Answers (1)

R Sahu
R Sahu

Reputation: 206577

You forgot to reset the value of arr->base after the call to realloc.

Use:

    p = (int *)realloc(arr->base, arr->max*2*sizeof(int));
    if(p != NULL){
        arr->max *= 2;  
        arr->base = p; // Missing line
        cout<<"reallocate successful base = " << arr->base << endl;
    }else{
        cout<<"reallocate failed base = "<< arr->base <<endl;
    }

Upvotes: 4

Related Questions