Logo

Navigation
  • Home
  • Services
    • ERP Solutions
    • Implementation Solutions
    • Support and Maintenance Solutions
    • Custom Solutions
    • Upgrade Solutions
    • Training and Mentoring
    • Web Solutions
    • Production Support
    • Architecture Designing
    • Independent Validation and Testing Services
    • Infrastructure Management
  • Expertise
    • Microsoft Development Expertise
    • Mobile Development
    • SQL Server Database and BI
    • SAP BI, SAP Hana, SAP BO
    • Oracle and BI
    • Oracle RAC
  • Technical Training
    • Learn Data Management
      • Business Intelligence
      • Data Mining
      • Data Modeling
      • Data Warehousing
      • Disaster Recovery
    • Learn Concepts
      • Application Development
      • Client Server
      • Cloud Computing Tutorials
      • Cluster Computing
      • CRM Tutorial
      • EDI Tutorials
      • ERP Tutorials
      • NLP
      • OOPS
      • Concepts
      • SOA Tutorial
      • Supply Chain
      • Technology Trends
      • UML
      • Virtualization
      • Web 2.0
    • Learn Java
      • JavaScript Tutorial
      • JSP Tutorials
      • J2EE
    • Learn Microsoft
      • MSAS
      • ASP.NET
      • ASP.NET 2.0
      • C Sharp
      • MS Project Training
      • Silverlight
      • SQL Server 2005
      • VB.NET 2005
    • Learn Networking
      • Networking
      • Wireless
    • Learn Oracle
      • Oracle 10g
      • PL/SQL
      • Oracle 11g Tutorials
      • Oracle 9i
      • Oracle Apps
    • Learn Programming
      • Ajax Tutorial
      • C Language
      • C++ Tutorials
      • CSS Tutorial
      • CSS3 Tutorial
      • JavaScript Tutorial
      • jQuery Tutorial
      • MainFrame
      • PHP Tutorial
      • VBScript Tutorial
      • XML Tutorial
    • Learn Software Testing
      • Software Testing Types
      • SQA
      • Testing
  • Career Training
    • Career Improvement
      • Career Articles
      • Certification Articles
      • Conflict Management
      • Core Skills
      • Decision Making
      • Entrepreneurship
      • Goal Setting
      • Life Skills
      • Performance Development
      • Personal Excellence
      • Personality Development
      • Problem Solving
      • Relationship Management
      • Self Confidence
      • Self Supervision
      • Social Networking
      • Strategic Planning
      • Time Management
    • Education Help
      • Career Tracks
      • Essay Writing
      • Internship Tips
      • Online Education
      • Scholarships
      • Student Loans
    • Managerial Skills
      • Business Communication
      • Business Networking
      • Facilitator Skills
      • Managing Change
      • Marketing Management
      • Meeting Management
      • Process Management
      • Project Management
      • Project Management Life Cycle
      • Project Management Process
      • Project Risk Management
      • Relationship Management
      • Task Management
      • Team Building
      • Virtual Team Management
    • Essential Life Skills
      • Anger Management
      • Anxiety Management
      • Attitude Development
      • Coaching and Mentoring
      • Emotional Intelligence
      • Stress Management
      • Positive Thinking
    • Communication Skills
      • Conversation Skills
      • Cross Culture Competence
      • English Vocabulary
      • Listening Skills
      • Public Speaking Skills
      • Questioning Skills
    • Soft Skills
      • Assertive Skills
      • Influence Skills
      • Leadership Skills
      • Memory Skills
      • People Skills
      • Presentation Skills
    • Finding a Job
      • Etiquette Tips
      • Group Discussions
      • HR Interviews
      • Interview Notes
      • Job Search Tips
      • Resume Tips
      • Sample Resumes
 

C Programming – Dynamic Memory allocation

By Brian Moriya | on May 29, 2006 |
C Language

Embedded and other low-memory footprint applications need to be easy on the amount of memory they use when executing.  In such scenarios, statically sized data types and data structures just are not going to solve your problem.  The best way to achieve this is by allocation of memory for variables at runtime under your watchful eye. This way your program is not using more memory than it has to at any given time. However, it is important to note that the amount of memory that can be allocated by a call to any of these functions is different on every operating system.

Dynamic Memory Allocation

malloc, calloc, or realloc are the three functions used to manipulate memory.  These commonly used functions are available through the stdlib library so you must include this library in order to use them.

  1.  #include stdlib.h

After including the stdlib library you can use the malloc, calloc, or realloc functions to manipulate chunks of memory for your variables.

Dynamic Memory Allocation Process

When a program executes, the operating system gives it a stack and a heap to work with. The stack is where global variables, static variables, and functions and their locally defined variables reside. The heap is a free section for the program to use for allocating memory at runtime.

Allocating a Block of Memory

Use the malloc function to allocate a block of memory for a variable. If there is not enough memory available, malloc will return NULL.

The prototype for malloc is:

  1. void *malloc(size_t size);

Do not worry about the size of your variable, there is a nice and convenient function that will find it for you, called sizeof. Most calls to malloc will look like the following example:

  1. ptr = (struct mystruct*)malloc(sizeof(struct mystruct));

This way you can get memory for your structure variable without having to know exacly how much to allocate for all its members as well.

Allocating Multiple Blocks of Memory

You can also ask for multiple blocks of memory with the calloc function:

  1. void *calloc(size_t num, size_t size);

If you want to allocate a block for a 10 char array, you can do this:

  1. char *ptr; 
  2. ptr = (char *)calloc(10, sizeof(char));

The above code will give you a chunk of memory the size of 10 chars, and the ptr variable would be pointing to the beginning of the memory chunk. If the call fails, ptr would be NULL.

Releasing the Used Space

All calls to the memory allocating functions discussed here, need to have the memory explicitly freed when no longer in use to prevent memory leaks. Just remember that for every call to an *alloc function you must have a corresponding call to free.

The function call to explicitly free the memory is very simple and is written as shown here below:

  1. free(ptr);

Just pass this function the pointer to the variable you want to free and you are done.

To Alter the Size of Allocated Memory

Lets get to that third memory allocation function, realloc.

  1. void *realloc(void *ptr, size_t size);

Pass this function the pointer to the memory you want to resize and the new size you want to resize the allocated memory for the variable you want to resize.

Here is a simple and trivial example to give you a quick idea of how you might see calloc and realloc in action. You will have many chances for malloc viewing as it is the most popular of the three by far.

allocation.c:

  1.  #include <stdio.h>
  2.  #include <stdlib.h>
  3. void main() {
  4. char *ptr, *retval;
  5. ptr = (char *)calloc(10, sizeof(char));
  6. if (ptr == NULL)
  7. printf("calloc failed\n");
  8. else
  9. printf("calloc successful\n");
  10. retval = realloc(ptr, 5);
  11. if (retval == NULL)
  12. printf("realloc failed\n");
  13. else
  14. printf("realloc successful\n");
  15. free(ptr);
  16. free(retval);
  17. }

First we declared two pointers and allocated a block of memory the size of 10 chars for ptr using the calloc function. The second pointer retval is used for getting the return value from the call to realloc. Then we reallocate the size of ptr to 5 chars instead of 10. After we check whether all went well with that call, we free up both pointers.

You can play around with the values of size passed to either of the memory allocation functions to see how big a chunk you can ask for before it fails on you. Do not worry, your operating system has the ability to keep your program in check, you will not hurt it this way.

Here is the output:

  1. ~/Projects/C_tutorials/dynamic memory allocation/samples $ ./all
  2. ocation
  3. calloc successful
  4. realloc successful
  5. ~/Projects/C_tutorials/dynamic memory allocation/samples $
« « C Programming – Pointers
C Programming – Linked Lists » »

Author Description

Avatar

Free Training

RSSSubscribe 392 Followers
  • Popular
  • Recent
  • C Programming – Decision Making – Looping

    April 4, 2006 - 0 Comment
  • Concept of Pixel in C Graphics

    July 11, 2006 - 0 Comment
  • C Programming – Arrays

    April 13, 2006 - 0 Comment
  • TSR in C – An Introduction

    July 11, 2006 - 0 Comment
  • C Programming – Handling of Character String

    April 17, 2006 - 0 Comment
  • C Programming – Data Types : Part 2

    August 21, 2011 - 0 Comment
  • C Programming – An Overview

    March 2, 2006 - 0 Comment
  • C Programming – Functions (Part-II)

    May 22, 2006 - 0 Comment
  • C Doubly Linked Lists

    June 26, 2011 - 0 Comment
  • C Programming – Constants and Identifiers

    March 2, 2006 - 0 Comment
  • C Programming – Data Types : Part 2

    August 21, 2011 - 0 Comment
  • C Circular Linked Lists

    June 26, 2011 - 0 Comment
  • C Doubly Linked Lists

    June 26, 2011 - 0 Comment
  • TSR in C – An Introduction

    July 11, 2006 - 0 Comment
  • Concept of Pixel in C Graphics

    July 11, 2006 - 0 Comment
  • Call by Value and Call by Reference

    July 6, 2006 - 0 Comment
  • C Language – The Preprocessor

    May 31, 2006 - 0 Comment
  • C Programming – File management in C

    May 31, 2006 - 0 Comment
  • C Programming – Linked Lists

    May 29, 2006 - 0 Comment
  • C Programming – Pointers

    May 25, 2006 - 0 Comment

Exforsys e-Newsletter

ebook
 

Related Articles

  • C Programming – Data Types : Part 2
  • C Circular Linked Lists
  • C Doubly Linked Lists
  • TSR in C – An Introduction
  • Concept of Pixel in C Graphics

Latest Articles

  • Project Management Techniques
  • Product Development Best Practices
  • Importance of Quality Data Management
  • How to Maximize Quality Assurance
  • Utilizing Effective Quality Assurance Strategies
  • Sitemap
  • Privacy Policy
  • DMCA
  • Trademark Information
  • Contact Us
© 2023. All Rights Reserved.IT Training and Consulting
This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish.AcceptReject Read More
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT