ArticleslgStudy

computer science

C dynamic memory allocation

C dynamic memory allocation is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand C dynamic memory allocation rather than just read about it. In short: C dynamic memory allocation refers to performing manual memory management for dynamic memory allocation in the C programming language via a group of functions in the C standard library, mainly malloc, realloc, calloc, aligned_alloc and free. The C++ programming language includes these functions; however, the operators new and delete provide similar functionality and are recommended by that language's authors.

Key takeaways

  • C dynamic memory allocation belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect C dynamic memory allocation to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of C dynamic memory allocation from memory before moving on to harder problems.

Reference excerpt

C dynamic memory allocation refers to performing manual memory management for dynamic memory allocation in the C programming language via a group of functions in the C standard library, mainly malloc, realloc, calloc, aligned_alloc and free. The C++ programming language includes these functions; however, the operators new and delete provide similar functionality and are recommended by that language's authors. Still, there are several situations in which using new/delete is not applicable, such as garbage collection code or performance-sensitive code, and a combination of malloc and new may be required instead of the higher-level new operator. Many different implementations of the actual memory allocation mechanism, used by malloc, are available. Their performance varies in both execution time and required memory.

Rationale The C programming language manages memory statically, automatically, or dynamically. Static-duration variables are allocated in main memory, usually along with the executable code of the program, and persist for the lifetime of the program; automatic-duration variables are allocated on the stack and come and go as functions are called and return. For static-duration and automatic-duration variables, the size of the allocation must be compile-time constant (except for the case of variable-length automatic arrays). If the required size is not known until run-time (for example, if data of arbitrary size is being read from the user or from a disk file), then using fixed-size data objects is inadequate. The lifetime of allocated memory can also cause concern. Neither static- nor automatic-duration memory is adequate for all situations. Automatic-allocated data cannot persist across multiple function calls, while static data persists for the life of the program whether it is needed or not. In many situations the programmer requires greater flexibility in managing the lifetime of allocated memory. These limitations are avoided by using dynamic memory allocation, in which memory is more explicitly (but more flexibly) managed, typically by allocating it from the heap (free storage), an area of memory structured for this purpose. In C, 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 deallocates the memory so that it can be used for other purposes. The original description of C indicated that calloc and cfree were in the standard library, but not malloc. Code for a simple model implementation of a storage manager for Unix was given with alloc and free as the user interface functions, and using the sbrk system call to request memory from the operating system. The 6th Edition Unix documentation gives alloc and free as the low-level memory allocation functions. The malloc and free routines in their modern form are completely described in the 7th Edition Unix manual. Some platforms provide library or intrinsic function calls which allow run-time dynamic allocation from the C stack rather than the heap (e.g. alloca()). This memory is automatically freed when the calling function ends.

Overview of functions The C dynamic memory allocation functions are defined in <stdlib.h> header (<cstdlib> header in C++).

Differences between malloc() and calloc() malloc() takes a single argument (the amount of memory to allocate in bytes), while calloc() takes two arguments — the number of elements and the size of each element. malloc() only allocates memory, while calloc() allocates and sets the bytes in the allocated region to zero.

Usage example Creating an array of ten integers with automatic scope is straightforward in C:

However, the size of the array is fixed at compile time. If one wishes to allocate a similar array dynamically without using a variable-length array, which is not guaranteed to be supported in all C11 implementations, an array can be allocated using malloc, which returns a void pointer (indicating that it is a pointer to a region of unknown data type), which can be cast for safety.

This computes the number of bytes that ten integers occupy in memory, then requests that many bytes from malloc and assigns the result to a pointer named a (due to C syntax, pointers and arrays can be used interchangeably in some situations). Because malloc might not be able to service the request, it might return a null pointer and it is good programming practice to check for this:

When the program no longer needs the dynamic array, it must eventually call free to return the memory it occupies to the free store:

The memory set aside by malloc is not initialized and may contain cruft: the remnants of previously used and discarded data. After allocation with malloc, elements of the array are uninitialized variables. The command calloc will return an allocation that has already been cleared:

With realloc we can resize the amount of memory a pointer points to. For example, if we have a pointer acting as an array of size n and we want to change it to an array of size m, we can use realloc.

Note that realloc must be assumed to have changed the base address of the block (i.e. if it has failed to extend the size of the original block, and has therefore allocated a new larger block elsewhere and copied the old contents into it). Therefore, any pointers to addresses within the original block are also no longer valid.

Type safety As stated earlier, malloc returns a void pointer (void*), which indicates that it is a pointer to a region of unknown data type. The use of casting is required in C++ due to the strong type system, whereas this is not the case in C. One may "cast" (see type conversion) this pointer to a specific type:

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with C dynamic memory allocation

Start with the simplest possible case. Write down what C dynamic memory allocation claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to C dynamic memory allocation before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about C dynamic memory allocation ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of C dynamic memory allocation

In research
C dynamic memory allocation appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses C dynamic memory allocation in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
C dynamic memory allocation is common in secondary-school and first-year university syllabi. It links to neighbouring topics C++, C standard library, Memory management, so understanding it makes those chapters shorter.
In everyday life
Look for C dynamic memory allocation outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “C dynamic memory allocation” →

How to study C dynamic memory allocation in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what C dynamic memory allocation means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain C dynamic memory allocation out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is C dynamic memory allocation in simple terms?

C dynamic memory allocation refers to performing manual memory management for dynamic memory allocation in the C programming language via a group of functions in the C standard library, mainly malloc, realloc, calloc, aligned_alloc and free. The C++ programming language includes these functions; ho…

Why does C dynamic memory allocation matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study C dynamic memory allocation?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on C dynamic memory allocation.

Tags

  • C++
  • C standard library
  • Memory management
  • Memory management software

Keep exploring