YouTip LogoYouTip

C Memory Management

C Memory Management

C Memory Management

-- Learning is not just about technology, but also dreams!

C Tutorial

C Language TutorialC IntroductionC Environment SetupC VScodeC Program StructureC Basic SyntaxC Data TypesC VariablesC ConstantsC Storage ClassesC OperatorsC Decision MakingC LoopsC FunctionsC Scope RulesC ArraysC enum (Enumeration)C PointersC Function Pointers and Callback FunctionsC StringsC StructuresC UnionsC Bit FieldsC typedefC Input & OutputC File I/OC PreprocessorsC Header FilesC Type CastingC Error HandlingC RecursionC Variable ArgumentsC Memory ManagementC Undefined BehaviorC Command Line ArgumentsC Safe FunctionsC Sorting AlgorithmsC Project StructureC ExamplesC Classic 100 ExamplesC Quiz

C Standard Library

C Standard Library - Reference Manual<a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library -

C Variable Arguments

C Undefined Behavior

C Memory Management

This chapter explains dynamic memory management in C. The C language provides several functions for memory allocation and management. These functions can be found in the header file.

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

Number Function and Description
1 void *calloc(int num, int size); Dynamically allocates num contiguous blocks of memory in the heap, each of size size bytes, and initializes every byte to 0. Therefore, the result is a memory block of num*size bytes, with each byte set to 0.
2 void free(void *address); This function releases the memory block pointed to by address, freeing dynamically allocated memory.
3 void *malloc(int num); Allocates a specified-size memory block in the heap for storing data. This memory block is not initialized after function execution, so its values are unknown.
4 void *realloc(void *address, int newsize); This function reallocates memory, expanding the memory block to newsize.

Note: The void * type represents a pointer of undetermined type. C and C++ specify that the void * type can be forcibly cast to any other type of pointer.

Dynamic Memory Allocation

When programming, if you know the size of an array in advance, defining the array is straightforward. For example, an array to store names can hold up to 100 characters, so you can define the array as follows:

char name;

However, if you do not know the required text length in advanceβ€”for instance, when storing a detailed description on a topicβ€”you need to define a pointer that points to a character for which the memory size is not yet defined, and then allocate memory based on requirements, as shown below:

Example

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main() {
    char name;
    char *description;

    strcpy(name, "Zara Ali");

    /* Dynamically allocate memory */
    description = (char *)malloc(200 * sizeof(char));

    if (description == NULL) {
        fprintf(stderr, "Error - unable to allocate required memoryn");
    } else {
        strcpy(description, "Zara ali a DPS student in class 10th");
    }

    printf("Name = %sn", name);
    printf("Description: %sn", 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(), simply by replacing malloc with calloc, as shown below:

calloc(200, sizeof(char));

When dynamically allocating memory, you have full control and can pass any size value. In contrast, arrays with predefined sizes cannot change size once defined.

Resizing and Releasing Memory

When a program exits, the operating system automatically releases all memory allocated to it. However, it is recommended that you always call the free() function to release memory when it is no longer needed.

Alternatively, you can call the realloc() function to increase or decrease the size of an already allocated memory block. Let's use realloc() and free() to review the above example again:

Example

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main() {
    char name;
    char *description;

    strcpy(name, "Zara Ali");

    /* Dynamically allocate memory */
    description = (char *)malloc(30 * sizeof(char));

    if (description == NULL) {
        fprintf(stderr, "Error - unable to allocate required memoryn");
    } else {
        strcpy(description, "Zara ali a DPS student.");
    }

    /* Suppose you want to store a larger description */
    description = (char *)realloc(description, 100 * sizeof(char));

    if (description == NULL) {
        fprintf(stderr, "Error - unable to allocate required memoryn");
    } else {
        strcat(description, "She is in class 10th");
    }

    printf("Name = %sn", name);
    printf("Description: %sn", description);

    /* Use free() to release memory */
    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 not reallocating extra memory; the strcat() function will generate an error because insufficient memory is available for storing the description.

Common Memory Management Functions and Operators in C

  • malloc() function: Used for dynamic memory allocation. It takes one argument, the size of memory to allocate (in bytes), and returns a pointer to the allocated memory.
  • free() function: Used to release previously allocated memory. It takes a pointer to the memory to be freed as an argument and marks that memory as unused.
  • calloc() function: Used for dynamic memory allocation and initializes it to zero. It takes two arguments, the number of memory blocks to allocate and the size of each 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, then attempts to resize the previously allocated memory block. If successful, it returns a pointer to the reallocated memory; otherwise, it returns a null pointer.
  • sizeof operator: Used to get the size (in bytes) of a data type or variable.
  • Pointer operator: Used to obtain the memory address or value of the variable pointed to by the pointer.
  • & operator: Used to obtain the memory address of a variable.
  • * operator: Used to obtain the value of the variable pointed to by the pointer.
  • -> operator: Used with pointers to access structure members, with the syntax pointer->member, equivalent to (*pointer).member.
  • memcpy() function: Used to copy data from a source memory area to a destination memory area. It takes three arguments, a pointer to the destination memory area, a pointer to the source memory area, and the size of data to copy (in bytes).
  • memmove() function: Similar to memcpy(), but it can handle overlapping memory areas. It takes three arguments, a pointer to the destination memory area, a pointer to the source memory area, and the size of data to copy (in bytes).

← Php Anonymous ClassesPhp Constant Arrays β†’