Reputation: 79
double * copyTemp=NULL;
double * output= malloc(sizeof(double*)*MallSize);
double test1[] = {1.2,2.2,3.1};
double test2[]={ 0.1,0.2,0.3,0.5,0.7,1.1,1.2,2.2};
int i=0;
int j=0;
addArrayInOrder(test1 ,test2,output , &counter,&i , &j,size1,size2);
ShrinkMemory ( MallSize, counter, output , copyTemp );
free(output); <- this part crashes for some reason
return 0;
the problem I am getting is that sometime when i call free the program cashes. I dont see any mistake in this code since I set temp to NULL already so only one thing is pointed to the array is the ans pointer. So I should be able to call free at the end of the program to release the memory.
The function looks like
void addArrayInOrder(double *array1, double *array2, double *final, int *finalCounter, int *arry1Counter, int *array2Counter, int ArrSize1, int ArrSize2)
{
while (*arry1Counter < ArrSize1 && *array2Counter < ArrSize2)
{
if (isEqual(array1, array2, *arry1Counter, *array2Counter))
{
*(final + *finalCounter) = *(array1 + *arry1Counter);
arry1Counter++;
(*array2Counter)++;
(*finalCounter)++;;
}
else if (*(array1 + *arry1Counter) > *(array2 + *array2Counter))
{
*(final + *finalCounter) = *(array2 + *array2Counter);
(*array2Counter)++;
(*finalCounter)++;
}
else
{
*(final + *finalCounter) = *(array1 + *arry1Counter);
(*arry1Counter)++;
(*finalCounter)++;
}
}
}
int ShrinkMemory(int MaxSize, int MinSize, double *final, double *temp)
{
if (MaxSize != MinSize)
{
temp = realloc(final, MinSize * sizeof(double *));
if (temp == NULL)
{
printf("relloc failed ! exixting /n");
return 1;
}
else
{
printf("fsafda %p \n",temp);
printf("fsafda %p \n",final);
final=temp;
temp=NULL;
printf("fsafda %p \n",temp);
printf("fsafda %p \n",final);
}
}
return 0;
}
why is it crashing? I even printed out the memory using prinf %p and the address looks right
Upvotes: 0
Views: 102
Reputation: 46249
You reassign final
within ShrinkMemory
and expect that to change what happens outside the function. C doesn't work like that. You need to use a double pointer (double **final
) and change every reference to final
to *final
.
Also to be clear, a "double pointer" in this case means a pointer to a pointer to something (the 2 asterisks specify that); the type of thing being pointed to has nothing to do with it (by coincidence it's a "double" datatype here)
Upvotes: 2
Reputation: 476940
For an array of doubles, you want:
double * output= malloc(sizeof(double) * MallSize);
// ^^^^^^^^^^^^^^
(Likewise for realloc
etc.)
Upvotes: 3