Answer: Each dynamic allocation function allocates requested chunk from the pool of available memory and returns a pointer pointing to the beginning of the block. The most common error is dereferencing the pointer without verifying whether allocation is successful or not. Dynamic allocation function returns NULL in the event of insufficient memory in the pool of available memory.
Because NULL pointer points to nowhere. Dereferencing it causes abnormal program termination. So, before performing indirection on pointer returned to by dynamic allocation function, make sure it’s not NULL.
In case of resizing the previously allocated block using realloc(), use the pointer returned by realloc() and not the previous pointer. For example,
int main(void) { int *pi, num; pi = (int *)malloc(num * sizeof(int)); /* make sure if chunk is allocated or not */ if (pi == NULL) { /* allocation failed, exit program */ } /* else use the chunk */ /* after your're done, free up memory */ return 0; }
The other very common error occurs when we mistakenly free up allocated chunk more than once or we try to free up a part of it. For example,
int *pi; int n = 10; pi = malloc(n * sizeof(int)); /* all are invalid */ free(pi + 5 ); /* freeing a part of it */ /* free up more than once */ free(pi); free(pi);
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Watch Advanced C Programming Videos
- Apply for Computer Science Internship
- Buy C Books
- Apply for C Internship
- Practice BCA MCQs