C language programming - memory management

Dynamic memory management in C language. The C language provides several functions for memory allocation and management. These functions can be found in the <stdlib.h> header file.

In C language, memory is managed through pointer variables. A pointer is a variable that stores a memory address that can point to a variable of any data type, including integers, floating point numbers, characters, and arrays. The C language provides some functions and operators that allow programmers to operate on memory, including allocation, release, movement, and copying.

Note: The void * type represents an untyped pointer. C and C++ stipulate that the void * type can be converted to any other type of pointer through type conversion.

dynamically allocate memory

When programming, it is easier to define an array if you know its size in advance. For example, an array that stores people's names can hold up to 100 characters, so you can define the array as follows:

char name[100];

However, if you don't know in advance the length of text you need to store, for example if you want to store a detailed description about a topic. Here, we need to define a pointer that points to a character whose required memory size is not defined, and then allocate memory according to the demand, as shown below:


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main()
{
   char name[100];
   char *description;
 
   strcpy(name, "Zara Ali");
 
   /* 动态分配内存 */
   description = (char *)malloc( 200 * sizeof(char) );
   if( description == NULL )
   {
      fprintf(stderr, "Error - unable to allocate required memory\n");
   }
   else
   {
      strcpy( description, "Zara ali a DPS student in class 10th");
   }
   printf("Name = %s\n", name );
   printf("Description: %s\n", description );
}

When the above code is compiled and executed, it produces the following result:

Name = Zara Ali
Description: Zara ali a DPS student in class 10th

The above program can also be written using calloc() , just replace malloc with calloc, as shown below:

calloc(200, sizeof(char));

When dynamically allocating memory, you have full control and can pass values ​​of any size. And those arrays with a pre-defined size cannot change the size once defined.

Resize and free memory

When the program exits, the operating system will automatically release all the memory allocated to the program. However, it is recommended that you call the function free() to release the memory when you do not need the memory.

Alternatively, you can increase or decrease the size of an allocated memory block by calling the function realloc() . Let's look at the above example again using the realloc() and free() functions:


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main()
{
   char name[100];
   char *description;
 
   strcpy(name, "Zara Ali");
 
   /* 动态分配内存 */
   description = (char *)malloc( 30 * sizeof(char) );
   if( description == NULL )
   {
      fprintf(stderr, "Error - unable to allocate required memory\n");
   }
   else
   {
      strcpy( description, "Zara ali a DPS student.");
   }
   /* 假设您想要存储更大的描述信息 */
   description = (char *) realloc( description, 100 * sizeof(char) );
   if( description == NULL )
   {
      fprintf(stderr, "Error - unable to allocate required memory\n");
   }
   else
   {
      strcat( description, "She is in class 10th");
   }
   
   printf("Name = %s\n", name );
   printf("Description: %s\n", description );
 
   /* 使用 free() 函数释放内存 */
   free(description);
}

When the above code is compiled and executed, it produces the following result:

Name = Zara Ali
Description: Zara ali a DPS student.She is in class 10th

You can try without reallocating extra memory, the strcat() function will generate an error because there is not enough memory available to store the description.

Commonly used memory management functions and operators in C language

  • malloc() function: used to dynamically allocate memory. It takes one parameter, the size of the memory to be allocated in bytes, and returns a pointer to the allocated memory.

  • free() function: used to release previously allocated memory. It takes as argument a pointer to the memory to be freed and marks that memory as unused.

  • calloc() function: used to dynamically allocate memory and initialize it to zero. It takes two parameters, the number of memory blocks to allocate and the size of each memory block in bytes, and returns a pointer to the allocated memory.

  • realloc() function: used to reallocate memory. It takes two arguments, a previously allocated pointer and a new memory size, and then tries to resize the previously allocated memory block. It returns a pointer to the reallocated memory if the adjustment was successful, or a null pointer otherwise.

  • sizeof operator: Used to get the size (in bytes) of a data type or variable.

  • Pointer operator: Used to obtain the value of the memory address or variable pointed to by the pointer.

  • & Operator: Used to get the memory address of a variable.

  • * operator: used to obtain the value of the variable pointed to by the pointer.

  • -> operator: used for pointer access to structure members, the syntax is pointer->member, which is equivalent to (*pointer).member.

  • memcpy() function: used to copy data from source memory area to target memory area. It takes three parameters, a pointer to the destination memory area, a pointer to the source memory area, and the size of the data to be copied in bytes.

  • memmove() function: Similar to the memcpy() function, but it can handle overlapping memory regions. It takes three parameters, a pointer to the destination memory area, a pointer to the source memory area, and the size of the data to be copied in bytes.

There is no essential difference between malloc and calloc. The uninitialized memory after malloc can be initialized with memset.

The main difference is that malloc does not initialize allocated memory, and calloc initializes allocated memory to zero.

The minor difference is that calloc returns an array, while malloc returns an object.

Calloc is equal to malloc and then memset, so malloc is more efficient than calloc.

The calling form of the function malloc to allocate memory space: (type specifier *) malloc (size).

Allocation of memory space function calloc calloc is also used to allocate memory space.

Why use malloc more and rarely calloc?

Because calloc has initialized the memory (all initialized to 0),

calloc is equivalent to

p = malloc();

memset(p, 0,size);

Compared with malloc, there are more operations to write zeros to memory, and we sometimes need to write zeros, but most of the time we don't.

 

Guess you like

Origin blog.csdn.net/shiwei0813/article/details/131464998