Reputation: 33
Hi i have a source code C as below:
#include <stdio.h>
#include <stdlib.h>
void test(int *a,int n)
{
a=(int*)malloc(n * sizeof(int));
for(int i=0;i<n;i++)
a[i] = i+1;
}
int main()
{
int *ptr;
int n;
n = 5;
printf("Enter number of elements: %d\n", n);
test(ptr,n);
if (ptr == NULL) {
printf("Memory not allocated.\n");
}
else {
//...
}
return 0;
}
As my understanding, when we call function test, the program will create a shadow of pointer
ptr to put inside test and then when we go out of test the shadow of ptr will be delete so in the main()
the ptr still be NULL
, but inside the test we have malloc
a memory for ptr and this memory is in the heap
and it is not free when we go out of test. So if i call test many time this will make memory leak is this true ? And how can i free this memory with free()
function in the main ?
Upvotes: 1
Views: 124
Reputation: 2930
void test(int *a,int n)
{
a=(int*)malloc(n * sizeof(int));
for(int i=0;i<n;i++)
a[i] = i+1;
}
this will lead to memory leak for sure!. No call was encountered to free(void* buffer)
before existing the test function. you are getting a copy of the user pointer, since evrey thing is passed by value
in C, that means each operation on the copy pointer a
will not mirrored or affects the calle pointer (ptr
). how to fix?
change the function signature to recieve double pointer! And calling free()
before rturn from main if malloc succedd to allocate.
Remember: Allways check malloc()
system call return !!
see fixes below:
#include <stdio.h>
#include <stdlib.h>
void test(int **a,int n)
{
int* temp=(int*)malloc(n * sizeof(int));
if(!temp) /*always check malloc system call return*/
{
*a = NULL;
return;
}
*a = temp;
for(int i=0;i<n;i++)
a[i] = i+1;
}
int main()
{
int* ptr = NULL;
...
test(&ptr, n);
if(!ptr){
perror("malloc failed"); /*write to standard error*/
exit(EXIT_FAILURE);
}
... do work ..
/*if we reach this code it means that malloc succedd then free the ptr which points to the previous allocated heap buffer*/
free(ptr);
return 0;
}
Upvotes: 1
Reputation: 213678
As my understanding, when we call function test, the program will create a shadow of pointer ptr to put inside test and then when we go out of test the shadow of ptr will be delete so in the main() the ptr still be NULL, but inside the test we have malloc a memory for ptr and this memory is in the heap and it is not free when we go out of test. So if i call test many time this will make memory leak is this true ?
Your understanding is correct. It's enough to call the function once to get a memory leak.
And how can i free this memory with free() function in the main ?
You must return the pointer to the caller in order to enable that. See this:
Dynamic memory access only works inside function
Upvotes: 2