- What is Memory leak in C and how can we avoid it.
- Can array size be declared at run time.
- What happens when we try to access NULL pointer in C.
What is Memory leak in C and how can we avoid it.
Memory leak happens when programmer allocated memory in heap but don’t release it back to the heap. Memory leak reduces the available memory for program and as a result the performance of program reduces.
Here is an example of memory leak:
#include <stdio .h> #include <stdlib.h> void getSometing(){ /* Dynamically declare memory for an integer array of 10 elements */ int *array = (int *) malloc(10*sizeof(int)); /* Do something and return without releasing allocated memory */ return; } int main() { int i; for(i = 0; i<100; i++){ getSometing(); } return 0; }
In above program, function getSometing dynamically allocates memory an array but then returns without deallocating it. Every time getSometing function is called it reduces the available memory for the program. To avoid memory leaks, getSometing function should release allocated memory using free.
void getSometing(){ /* Dynamically declare memory for an integer array of 10 elements */ int *array = (int *) malloc(10*sizeof(int)); /* Do something and release allocated memory */ free(array); return; }
Can array size be declared at run time.
The size of the array must be known to compiler during compile time. However, If we don’t know the length of array at compile time then we can dynamically allocate arrays using malloc and calloc function.
What happens when we try to access NULL pointer in C.
As we know that, NULL pointer in C is a pointer which is pointing to nothing. If we try to access the memory location pointed by a null pointer, program can crash.