In this article I would like to provide few tips related to memory management when we use C libraries malloc(), calloc() and free() functions.
Whenever possible, try to use static buffers where compiler automatically frees such memory. Make sure that, previously allocated memory is freed manually.
malloc():
The library function malloc is used to allocate a block of memory on the heap. The program accesses this block of memory via a pointer that malloc returns. When the memory is no longer needed, the pointer is passed to free which de-allocates the memory so that it can be used for other purposes.
When you are allocating memory using malloc, make sure that that 0 (zero) bytes are not allocated. According to the documentation, behaviour for malloc() for this case is undefined. Always check for the pointer to the memory returned by calloc/malloc. If this pointer is NULL then the memory allocation should be considered unsuccessful and no operations should be performed using that pointer.
free():
The library function free(void *ptr) de-allocates the memory previously allocated by a call to calloc, malloc, or realloc.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
#include <stdio.h> int main() { int no_emements, i, *ptr, sum = 0; printf("\n\nEnter number of elements: "); scanf("%d", &no_elements); // dynamic memory allocation using malloc() ptr = (int *) malloc(no_emements*sizeof(int)); if(ptr == NULL) // if empty array { printf("\n\nError! Memory not allocated\n"); return 0; // exit from program } printf("\n\nEnter elements of array: \n\n"); for(i = 0; i < no_elements; i++) { // storing elements at contiguous memory locations scanf("%d", ptr+i); sum = sum + *(ptr + i); } // printing the array elements using pointer to the location printf("\n\nThe elements of the array are: "); for(i = 0; i < no_elements; i++) { printf("%d ",ptr[i]); // ptr[i] is same as *(ptr + i) } /* freeing memory of ptr allocated by malloc using the free() method */ free(ptr); return 0; } |
Check and run the program here:
You can run the above program on codeboard editor and see the results. You are allowed to modify code and run. In the editor there is a menu at the top-right corner. Here you can see two buttons such as ‘Compile’ and ‘Run’.
Software engineer by profession, and owned troubleshotyourself channel. Enthusiastic blogger and love to write articles on computer technology and programming. Reach me at kiran.troubleshootyourself@gmail.com.
- Article ends here -