I allocated memory to a pointer, which i had to return. So I don't know where to free it as its a local variable. I was trying to create an array of variable length (user-specified). I got some help for that in this forum only under this thread
here is the code
#include <stdio.h>
void printArray(int arr [], int size);
int * readArray(int size);
int main(){
int size;
printf("Enter the size of the array ");
scanf("%d",&size);
printArray(readArray(size),size);
getchar();
return 0;
}
int * readArray(int size){
int *A = malloc ( size * sizeof *A );
int i;
for (i=0;i<size;i++){
printf("\nEnter the element no. %d: ",i+1);
scanf("%d",(A+i));
}
// free(A); this when uncommented cause the first element to be zero, makes sense, but
// why other values are not lost
return A; // Here i return the pointer.
}
void printArray(int *arr, int size){
int i=0;
for (i=0; i<size;i++){
printf("%d ", *(arr++));
}
printf("\n");
getchar();
}
Should I free it before returning it? If yes then how? Or should I free it in main, will it be known there ?
A sample Output of the program when I free pointer A before returning it is uploaded in image.