C++Builder How To Use The Realloc() Function In C++ Programs

FireWind

Свой
Регистрация
2 Дек 2005
Сообщения
1,957
Реакции
1,203
Credits
4,034
How To Use The Realloc() Function In C++ Programs
By Yilmaz Yoru August 26, 2021

How can we use memory in C and C++? How can I reallocate something in memory? How can I manage memory dynamically? What kind of memory methods or functions are used for the Dynamic Memory Management? How can I use malloc()? How can I use free()? How can I use realloc()?

In computers, all data and operations during runtime is stored in the memory of our computers, IoTs, or in other microdevices. This memory is generally a RAM (Для просмотра ссылки Войди или Зарегистрируйся) that allows data items to be read or written in almost the same amount of time irrespective of the physical location of data inside the memory.

In general, In programming, there are two kinds of memory allocations, Static Memory Allocation, and Dynamic Memory Allocation.

What is static memory allocation in a C++ program?​

Static Memory Allocation is a memory allocation method that is defined by variable definitions when programming and it has a fixed size, can not be changed during the run-time. These variables are defined variables in our programs like constants, strings, pointers, arrays, and structures. When a program is compiled, the compiler allocates part of the memory to store data. This is called Static Memory Allocation or Compile-time Memory. There are limitations in such static memory allocation to use these kinds of variables. Because:

These allocations are done in memory exclusively allocated to a program, we can’t increase the size of static allocations to handle more new elements. Thus, this may result to declare larger arrays than required which means a waste of memory usage. If we used less data than expected, Static Memory Allocations don’t allow us to reduce array size to save memory. It is hard to create advanced dynamic data structures which can be deleted, reallocated variables, linked lists, trees, and other data, which are essential in most real-life programming situations.

What does dynamic memory allocation mean?​

Dynamic Memory Allocation is a memory allocation method in which the memory is allocated during the execution of a program (at run-time). Для просмотра ссылки Войди или Зарегистрируйся functions/methods involve the use of pointers and standard library functions. Sometimes we use pointers to point to the address of blocks of memory which is allocated dynamically. So we can easily access or operate on those dynamic memory allocations.

What are the key memory allocation functions in C and C++ programs?​

The C++ language is a great programming language with its ancestor C programming language. C programming language has both Static Memory Allocation and Dynamic Memory Allocation methods. Most used Dynamic Memory Allocation functions are defined in header <stdlib.h> and mostly we use malloc(), calloc(), realloc() and free().

FunctionSyntaxDescription
mallocvoid* malloc( size_t size );allocates a block of from memory heap and returns a pointer
callocvoid* calloc( size_t num, size_t size );allocates a block of from memory heap, initializes it to zero and returns a pointer
reallocvoid *realloc( void *ptr, size_t new_size );re-allocates the size of the allocated memory block,, copies the contents to a new location
freevoid free( void* ptr );Free block of memory blk allocated from memory heap
Let’s see how we use realloc() and free() functions.

Learn to use realloc() function​

Для просмотра ссылки Войди или Зарегистрируйся function is a Dynamic Memory Allocation function that reallocates main memory. realloc attempts to shrink or expand the previously allocated block to size bytes. If size is zero, the memory block is freed and NULL is returned. The block argument points to a memory block previously obtained by calling malloc, calloc, or realloc. If block is a NULL pointer, realloc works just like malloc.

realloc adjusts the size of the allocated block to size, copying the contents to a new location if necessary.

Syntax:
C++:
void *realloc( void *ptr, size_t new_size );

Learn to use malloc(), realloc() and free() functions together​

The Для просмотра ссылки Войди или Зарегистрируйся function is a Dynamic Memory Allocation function that frees allocated block. free() deallocates a memory block allocated by a previous call to Для просмотра ссылки Войди или Зарегистрируйся, Для просмотра ссылки Войди или Зарегистрируйся, or Для просмотра ссылки Войди или Зарегистрируйся.

Syntax:
C++:
void free( void* ptr );

Here is an example of how to use the C++ realloc(), malloc() and free() functions​

C++:
#include <stdio.h>
#include <alloc.h>
#include <string.h>
 
int main()
{
 char *str;
 
 
 if( str = (char *) malloc(20) )
 {
 strcpy(str, "LearnCPlusPlus.org");
 printf("Dynamic Memory Allocated :%s  Adress:%p\n", str, str);
 
 str = (char *) realloc(str, 50);
 printf("Dynamic Memory Allocated :%s  Adress:%p\n\n", str, str);
 /* free memory */
 }
 else
 {
 printf("Not enough memory to allocate buffer\n");
 exit(1); // Terminate program if out of memory
 
 }
 
 getchar();
 return 0;
}

Here is a full C++ example of using the C++ realloc() function​

C++:
#include <iostream>
 
int main()
{
 char *str;
 printf("realloc() example:\n");
 
 if( str = (char *) malloc(20) )
 {
 strcpy(str, "LearnCPlusPlus.org");
 std::cout << "Dynamic Memory Allocated :" << str
   << "  Adres:" << static_cast<void*>(str) <<std::endl;
 
 str = (char *) realloc(str, 50);
 std::cout << "Dynamic Memory Allocated :" << str
   << "  Adres:" << static_cast<void*>(str) <<std::endl;
 /* free memory */
 }
 else
 {
 std::cout <<  "Not enough memory to allocate buffer\n";
 exit(1); // Terminate program if out of memory
 
 }
 
 getchar();
 return 0;
}
As you see dynamically you can extend the size of allocated memory dynamically by using reallocate() function in C and C++ programming languages.