My question is regarding freeing allocated memory in different functions. So my code is structured something like this:
int main()
{
// Declare variables
double *val1, *val2;
// Call function 1
function1(&val);
// Call function 2
function2(&val2);
// Do some stuff .....
// Free dynamically allocated memory
free(val1);
free(val2);
// End program
return 0;
}
void function1(double *val1)
{
/* Allocate memory */
val1 = (double*) malloc(n1*sizeof(double));
if (val1 == NULL){
printf("Error: Memory not allocated!");
exit(0);
}
}
void function2(double *val2)
{
// Allocate memory
val2 = (double*) malloc(n2*sizeof(double));
if (val2== NULL){
printf("Error: Memory not allocated!");
// Here I want to free val1!
exit(0);
}
}
Meaning that some memory is allocated for val1 inside function1 and for val2 inside function2.
Now, the contents contained in val1 is not needed in function2, so I would at first sight not have to pass the pointer to val1.
However, if val2 is not allocated correctly I want to exit the program, but free any allocated memory first. Can I free the memory for val1 inside function2 without passing the pointer for val1?