Below is the C program which I am trying out. It allocates the memory for the required number of elements as per the user input, gets the elements for the user, prints the elements & the sum.
I am freeing the allocated memory using the free
function before the use ptr. However, it's not throwing any error and I am able to compile/run, print the array and also the sum, successfully. My understanding of malloc and free is that if we free the allocated memory and try to access it, it should throw an error at compile time? Kindly clarify this doubt.
Thank you.
#include<stdio.h>
#include<stdlib.h>
int main(void){
int num=0;
int *ptr=NULL;
int sum=0;
printf("Enter number of elements in an array: \n");
scanf("%d",&num);
ptr = (int *)malloc(num*sizeof(int));
if (ptr==NULL){
printf("Error: unable to allocate memory\n");
exit(EXIT_FAILURE);
}
free(ptr); //ERROR NOT TRIGGERED
printf("Enter the elements of the array: \n");
for(int i=0;i<num;i++){
scanf("%d",(ptr+i));
sum += *(ptr+i);
}
printf("\nArray Elements are: \n");
for(int i=0;i<num;i++){
printf("%d ",*(ptr+i));
}
printf("\nSum of array elements are: %d\n", sum);
return 0;
}