Common Errors During Dynamic Memory Allocation in C

Question5: What are Common Errors Which Might Occur While Memory Being Allocated Dynamically in C?

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,

advertisement
advertisement
    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.

If you wish to look at all C Tutorials, go to C Tutorials.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.