Fundamentals 31 min read

Dynamic Memory Allocation, malloc/free, new/delete, and Linux Memory Management Overview

This article explains the principles and usage of dynamic memory allocation in C/C++ (malloc, calloc, realloc, free, new, delete), compares their behaviors, demonstrates common pitfalls, and extends the discussion to Linux kernel memory statistics, cache handling, swappiness tuning, and garbage‑collection concepts.

Deepin Linux
Deepin Linux
Deepin Linux
Dynamic Memory Allocation, malloc/free, new/delete, and Linux Memory Management Overview

1. Dynamic Memory Allocation

When the required size of an array is unknown at compile time, a program must allocate a sufficiently large block of memory at runtime; otherwise it risks out‑of‑bounds errors.

If the allocated block is larger than needed, unused memory is wasted; if it is too small, index‑overflow errors occur. Dynamic memory allocation solves both problems by allocating exactly the amount requested during execution.

malloc and free

The C standard library provides malloc and free for dynamic allocation and deallocation.

void *malloc(size_t size);
void free(void *pointer);

malloc receives the number of bytes to allocate. If enough memory is available it returns a pointer to the start of the block; otherwise it returns NULL . Every returned pointer must be checked for NULL .

free accepts either NULL or a pointer previously returned by malloc , calloc or realloc . All dynamically allocated memory resides on the heap and is accessed through a pointer stored on the stack.

malloc function details

malloc returns a void* which can be cast to any other pointer type. The allocated memory is uninitialized.

Allocated size is at least the requested number of bytes.

The return value points to the beginning of a usable region.

Multiple malloc calls must not return overlapping regions unless a previous block has been freed.

Allocation should be fast and return promptly.

An implementation should also provide realloc and free .

Example usage:

#include
#include
#include
int main() {
    char *ptr;
    ptr = (char*)malloc(8);   // cast from void*
    if (NULL == ptr) {
        exit(1);
    }
    if(ptr)
        printf("Memory Allocated at: %x\n",ptr);
    free(ptr);
    ptr = NULL; // avoid dangling pointer
    return 0;
}

realloc and calloc

calloc allocates n elements of size bytes each and zero‑initializes the memory:

void *calloc(size_t n, size_t size);

realloc changes the size of an existing block. If the block can be expanded in place the original pointer is returned; otherwise a new block is allocated, the old data are copied, and the old block is freed.

extern void *realloc(void *mem_address, unsigned int newsize);

If mem_address is NULL , realloc behaves like malloc .

If newsize is zero, the block is freed and NULL is returned.

If there is insufficient memory, NULL is returned and the original block remains unchanged.

new and delete (C++)

The C++ operators new and delete allocate memory and invoke constructors/destructors automatically.

int *pi = new int;               // uninitialized int
int *pi = new int(100);          // initialized to 100
string *ps = new string(10,'9'); // "9999999999"

When allocation fails, the non‑throwing form of new returns NULL ; the throwing form raises std::bad_alloc . Memory obtained with new must be released with delete , otherwise destructors are not run and leaks occur.

2. Linux Memory Release and Monitoring

Typical commands such as free , cat /proc/meminfo , and slabtop show total, free, cached, and buffered memory. The kernel keeps a list of free pages and uses it to satisfy allocation requests.

Key fields in /proc/meminfo include MemTotal , MemFree , Buffers , Cached , SwapTotal , SwapFree , Slab , VmallocUsed , etc.

Dropping caches

# echo 1 > /proc/sys/vm/drop_caches   # free pagecache
# echo 2 > /proc/sys/vm/drop_caches   # free dentries and inodes
# echo 3 > /proc/sys/vm/drop_caches   # free both

Before dropping caches, run sync to flush pending writes.

Swappiness

The kernel parameter vm.swappiness controls how aggressively the system swaps out pages. Values range from 0 (prefer physical RAM) to 100 (prefer swap). The default is 60.

# cat /proc/sys/vm/swappiness
# sysctl vm.swappiness=10   # temporary change
# echo "vm.swappiness = 10" >> /etc/sysctl.conf && sysctl -p   # permanent change

3. Memory Re‑allocation (realloc)

realloc can enlarge or shrink an existing block. If the block can be expanded in place the original pointer is returned; otherwise a new block is allocated, data are copied, and the old block is freed. If the request fails, NULL is returned and the original pointer remains valid.

#include
#include
int main(){
    int *p = (int*)malloc(5*sizeof(int));
    if(!p){ perror("malloc"); exit(1);}    
    // ... use p ...
    p = (int*)realloc(p, 10*sizeof(int));
    if(!p){ perror("realloc"); exit(1);}    
    free(p);
    return 0;
}

4. Garbage Collection Concepts

Automatic memory management (garbage collection) reclaims objects that are no longer reachable. Two classic algorithms are reference counting (now largely superseded) and reachability analysis using GC roots (stack, static fields, JNI locals, etc.).

Common GC algorithms:

Copying collector – simple and fast, but uses only half of the heap.

Mark‑Sweep – fully utilizes memory but can fragment the heap.

Mark‑Compact – eliminates fragmentation at the cost of moving live objects.

In the HotSpot JVM, the young generation typically uses a copying collector, while the old generation uses mark‑compact or concurrent mark‑sweep (CMS).

5. Additional Resources

For deeper study, refer to the Linux kernel documentation (e.g., Documentation/sysctl/vm.txt ), the /proc filesystem, and articles on memory management, mmap, and kernel data structures.

Garbage CollectionC++LinuxmallocMemory Allocationfreenew
Deepin Linux
Written by

Deepin Linux

Research areas: Windows & Linux platforms, C/C++ backend development, embedded systems and Linux kernel, etc.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.