Reputation: 2612
I have this program. I have heard that memory allocated with malloc can be freed outside of the function it was allocated in - but obviously I can't free z in main. Is there a memory leak in this program?
#include <stdio.h>
#include <stdlib.h>
int *add(int x, int y);
int main(int argc, char const *argv[]) {
int *x = NULL;
x = add(5, 4);
printf("%d\n", *x);
free(x);
return 0;
}
int *add(int x, int y) {
int *z = malloc(sizeof(int));
*z = x + y;
return z;
}
Upvotes: 3
Views: 91
Reputation: 4203
There is not. You allocate memory for one int
, and store that memory in the variable x
. You then free that memory when you free(x)
. You should, however, do a if(z == NULL)
check in your function.
Upvotes: 2
Reputation: 726509
No, your program would not result in a memory leak, because the memory block allocated that has been made inside the add()
function is properly freed in the main
function.
The only requirement for free
ing to be valid is that the pointer passed to free
came from malloc
, and has not been double-free
-d. The name of the variable to which the pointer is assigned does not matter.
The fact that the allocation and deallocation happen in different functions is not relevant as well. In fact, it is commonplace for programs with dynamic memory allocation to perform their allocations and deallocations inside different functions.
Upvotes: 2
Reputation: 16243
This code will not leak.
You're correctly free-ing the allocated memory.
Upvotes: 1