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 ?