So I'm implementing a heap using a resizable array and I keep getting this error every time it reallocates memory. The problem is with realloc ..I just can't figure out what's wrong with it. Here is the insert function:
void* insert (data_t *data, int room, long wake) {
if(data->size+1 == data->arraySize){
data->arraySize *= 2;
long l = (long)data->arraySize;
int* tempOne = realloc(data->heapElemOne, data->arraySize*sizeof(int));
long* tempTwo = realloc(data->heapElemTwo, l*sizeof(long));
if ( tempOne != NULL &&tempTwo !=NULL){ //realloc was
data->heapElemOne = tempOne;
data->heapElemTwo = tempTwo;
}
else{ //there was an error
printf("Error allocating memory!\n");
free(data->heapElemOne);
free(data->heapElemTwo);
return;
}
}
data->size++;
int now = data->size;
/*Adjust its position*/
if(data->size >0){
while(data->heapElemTwo[now/2] > wake && ((now/2)!=0))
{
data->heapElemTwo[now] = data->heapElemTwo[now/2];
data->heapElemOne[now] = data->heapElemOne[now/2];
now /= 2;
}
}
data->heapElemTwo[now] = wake;
data->heapElemOne[now] = room;`
And Here is part of the main:
int main(int argc, char *argv[]){
pthread_t r, c;
data_t data;
data.arraySize = 2;
data.size = 0;
long l = (long)data.arraySize;
data.heapElemOne = malloc(data.arraySize * sizeof(int));
data.heapElemTwo = malloc(l * sizeof(long));
Here's data_t declaration:
typedef struct{
int arraySize;
int* heapElemOne;
long* heapElemTwo;
int size;
int number;
pthread_mutex_t mutex;
pthread_cond_t more;
}data_t;
It relocated the memory to 4 but when it's changing it to 8 it gives an error. Been at it for ages and just can't figure it out -_- Thanks in advance!
malloc()
andrealloc()
you want to multiply the number of elements to be allocated bysizeof( int )
orsizeof( long )
depending on the type of data you store? - ua2bdata_t
. It sounds like you have apointer
&int
reference problem. - David C. Rankin