Introduction to C Language: Dynamic Memory Allocation Function malloc

This is the 45th article in the C language learning series.

The dynamic memory allocation function in C is: (int*)malloc(cols * sizeof(int))

This line of code is one of the core operations of dynamic memory allocation in C language.

We can break it down into several parts for better understanding:

1. malloc(cols * sizeof(int)) – Core allocation function

·malloc: This is a standard library function, and its name is an abbreviation for “memory allocation”. Its function is to request a block of contiguous memory space of a specified size from the operating system.

·cols * sizeof(int): This is the parameter passed to malloc, telling it how much memory to allocate. sizeof(int): This is an operator that calculates and returns the number of bytes an int type variable occupies on your system. For example, on most modern systems, the result of sizeof(int) is 4 (bytes). cols: This is a variable representing the number of integers you need. Therefore, cols * sizeof(int) means: I need the total number of bytes to store cols integers. For instance, if cols = 5, then it requests 5 * 4 = 20 bytes of contiguous space.

After executing malloc(20), the operating system will find a 20-byte unused free area in memory and return the starting address of this memory to you. If there is insufficient memory and no free area can be found, malloc will return NULL.

2. (int*) – Type casting

·Why is casting necessary? The return type of the malloc function is void* (generic pointer). This means it only knows that a block of memory has been allocated but does not know what type of data this memory will be used to store in the future.

·The role of (int*): This is called a forced type conversion. It tells the compiler: “Please convert the void* type address returned by malloc into a pointer to int type.”

·The purpose of doing this: Improve code readability: Clearly inform the reader of the code that this memory will be used as an integer array. Compatibility with C++: The C++ language requires that the return value of malloc must be forcibly type cast; although it can sometimes be omitted in C language, explicitly writing it is a very good habit. Avoid accidental errors: Make the type system clearer.

3. Overall meaning and result

The final result of the entire line of code (int*)malloc(cols * sizeof(int)) is:

Successfully allocated a contiguous block of memory sufficient to store cols integers and obtained a pointer of type int* pointing to the starting position of this memory.

You can use this pointer as an array name to access each integer in this memory using subscripts (ptr[0], ptr[1] …).

A complete example

Introduction to C Language: Dynamic Memory Allocation Function malloc

The program is explained as follows:

#include// stdio.h includes the definitions for scanf and printf

#include// stdlib includes the definitions for malloc and free

int main() {

int cols = 5;

int *ptr; // Declare a pointer to receive the allocated memory address

// Core operation: dynamically allocate memory

ptr = (int*)malloc(cols * sizeof(int));

// Very important: check if allocation was successful

if (ptr == NULL) {

printf(“Memory allocation failed!\n”);

return 1; // Abnormal exit

}

// Use this memory: just like using an array

for (int i = 0; i < cols; i++) {

ptr[i] = i * 10; // Assign values to the array

}

// Print array contents

printf(“Array contents: “);

for (int i = 0; i < cols; i++) {

printf(“%d “, ptr[i]);

}

free(ptr); // Finally, a crucial step: free the memory!

ptr = NULL; // Good habit: set pointer to NULL after freeing

return 0;

}

Program output:

Array contents: 0 10 20 30 40

Summary and analogy

You can think of this process as:

1.malloc: You go to the administrator (operating system) to request a piece of land. You only tell the administrator how much area you need (cols * sizeof(int)).

2.(int*): After you get the generic address (void*) of this land, you immediately put up a sign indicating “This is an integer parking lot” (int*), so that future vehicles (data) know how to park (how to store).

3.Assigning to int* ptr: You record the location (address) of this sign in your notebook (pointer variable ptr), so you can find this parking lot at any time.

Finally, remember: The memory allocated through malloc is not automatically reclaimed by the system; you must manually call free(ptr) to release it, otherwise it will lead to memory leaks.

In summary,the essence of dynamic memory allocation in C language is the malloc function, which is a key dialogue between the programmer and the operating system: requesting space, clarifying types, and safely releasing; every step is crucial to the program’s lifecycle.

I will conclude this article with an analogy:

Just like managing a smart parking lot, we use the malloc function to request parking spaces, specifying the size of the space when applying, and then use the free function to return the space; otherwise, the system will forever lose this memory space.

Introduction to C Language: Dynamic Memory Allocation Function malloc

Leave a Comment