Arrays. Memory allocation: malloc() and calloc() Operators new and delete

Dynamic memory allocation using the malloc library function consists of the following steps.

1. Including the malloc .h header file in the program with the #include directive .

2. Declaring a pointer of the desired type, for example int *p ;

3. Calling the malloc function, specifying the required amount of memory in bytes as a parameter. Since the function gives the result of its work as a pointer to the type void , a type cast is performed (the type of the result is converted to the type specified in the declaration). The resulting value is assigned to the declared pointer. Example:

p =(int *) malloc (number of array elements*sizeof (int ));

Instead of int can be substituted with any standard or programmer-introduced type.

4. Checking the fact of memory allocation. If it is not possible to allocate the required amount of memory, the malloc function returns as its result a NULL pointer corresponding to false. If the memory allocation is done, we continue the execution of the program, if not, we exit it with the appropriate diagnostics about the lack of memory. Example:

if (!p ) message, exit; else continuation;

5. Release of memory after the end of work with it. To do this, we call the fgee function and use the pointer as an argument:

free(p);

The pointer value obtained after step 3 must be retained until step 5 is completed. Otherwise, all memory allocated at this address will be lost when the program exits, which, ultimately, can lead to a lack of memory and disruption of the operating system .

Most common cause Computer “hangs” when working with dynamically allocated memory is a mismatch between the malloc and free instructions (the same pointer must be used in both instructions) or insufficient free memory.

As an example, consider the input / output of a one-dimensional dynamic array of arbitrary length, specified from the keyboard.

int i ,n ,*massiv ;//pointer declaration

cout<>n ;//array size input

massiv=(int*)malloc(n*sizeof(int));// dynamic memory allocation

if (!massiv )//check if memory is allocated

{cout<

cout<

getch();

return 0;)

cout<

for(i=0;i >massiv[i];//array input

cout<

for(i=0;i

free (array );//free memory

In this program, the pointer is only used to allocate dynamic memory. Further in the program, the array elements are accessed through the array name, which is the same as the pointer name.

You can also use the calloc() function to dynamically allocate memory. Unlike malloc, the calloc function, in addition to allocating a memory area for an array of objects, also initializes the array elements with zero values.

Depending on the version of C++ you are using, farmalloc(), farcalloc(), farcoreleft(), and farfree() functions can be used to work with large chunks of dynamic memory.

Your program must provide enough memory to remember the data being used. Some of these memory locations are allocated automatically. For example, we can declare

char place = "Bay of Pork's Liver";

and enough memory will be allocated to remember that string.

Or we can be more specific and request a certain amount of memory:

int plates;

This description allocates 100 memory locations, each dedicated to storing an integer value.

The C language doesn't stop there. It allows you to allocate additional memory while the program is running. Suppose, for example, you are writing an interactive program and do not know in advance how much data you will have to enter. You can allocate the amount of memory you need (as you think), and then, if necessary, require more. On fig. 15.5 is an example using the function malloc() to do just that. Also, pay attention to how such a program uses pointers.

/* add memory if needed */

#include

#define STOP " " /* signal to stop input */

#define BLOCK 100 /* memory bytes */

#define LIM 40 /* input string limit */

#define MAX 50 /* maximum number of input lines */

#define DRAMA 20000 /* long time delay */

charstore; /* source block of memory */

char symbol; /* input string receiver */

char*end; /* points to end of memory */

char*starts; /* points to the beginning of lines */

int index = 0; /* number of input lines */

int count; /* counter */

char*malloc(); /* memory allocator */

starts = store;

end = starts + BLOCK - 1;

puts("Name some symphony orchestras.");

puts("Enter one at a time: press the [enter] key at the beginning");

puts(" strings to complete your list. Okay, I'm done.");

while(strcmp(fgets(symph, LIM, stdin), STOP) != 0 && index< MAX)

( if(strlen(symph) > end - starts)

( /* actions when there is not enough memory to remember the input data */

puts(" Wait a second. I'll try to find more memory.");

end = starts + BLOCK - 1;

for(count = 0; count< DRAMA; count++);

puts("Found some!"); )

strcpy(starts , symph);

starts = starts + strlen(symph) + 1;

if(++index< MAX)

printf("This is %d. Continue if you like.n", index); )

puts("Okay, here's what I got:");

for(count = 0; count< index; count ++)

puts(starts);

RICE. 15.5. A program that adds memory on demand.

Here is an example of how the program works:

Name several symphony orchestras.

Enter them one by one; press the [enter] key at the beginning

lines to complete our list. O.k. I'm ready.

San Francisco Symphony.

This is 1. Continue if you like.

Chicago Symphony

This is 2. Continue if you like.

Berlin Philharmonic

This is 3. Continue if you like.

Moscow chamber

This is 4. Continue if you like. London Symphony

This is 5. Continue if you like. Vienna Philharmonic

Just a second. I'll try to find more memory.

Found some!

This is 6. Continue if you like.

Pittsburgh Symphony

This is 7. Continue if you like.

Okay, here's what I got:

san francisco symphony

Chicago Symphony

Berlin Philharmonic

Moscow chamber

London Symphony

Vienna Philharmonic

Pittsburgh Symphony

First let's see what the function does malloc(). It takes an unsigned integer argument that represents the number of bytes of memory required. So, malloc(BLOCK) requires 100 bytes. The function returns a pointer to the type char to the beginning of a new block of memory. We used the description

char*malloc();

to warn the compiler that malloc() returns a pointer to the type char. Therefore, we assigned the value of this pointer to an array element starts with the help of an operator

starts = malloc(BLOCK);

Okay, now let's look at the design of the program, which is to store all the source lines in a row in a large array store. We want to use starts to refer to the beginning of the first line, starts[l]- the second line, etc. At an intermediate stage, the program enters the string into the array symbol. We used fgets() instead of gets() to limit the input string to the length of the array symbol.

RICE. 15.6. Consecutive lines of symph written to the store array.

Before copying symbol V store, we need to check if there is enough space left for it. Pointer end refers to the end of memory, and the current value starts refers to the beginning of unused memory. So we can compare the difference between these two pointers with the length symbol and determine if there is enough memory left.

If there is not enough space, call malloc() to prepare additional memory. We install starts to the beginning of a new memory block, a end- at the end of the new block. Note that we do not have a name for this new memory. It is not, for example, an extension store. We only have pointers that refer to a new memory area.

When the program is running, each new line is referenced by an element of the array of pointers starts. Some lines are in store, others - in one or more new memory areas.

But as long as we have pointers, we can work with strings, as the print part of the program shows us.

So used malloc(). But suppose you want to work with memory like int, but not char. You can use here too malloc(). Here's how it's done:

char*malloc(); /* still declare as pointer to char */

int *newmem;

newmem = (int *) malloc(l00); /* use cast operation */

Again, 100 bytes are required. The cast operation converts the value returned by a type pointer char, into a pointer to type int. If, as in our system, int occupies two bytes of memory, which means that newmem+1 will increment the pointer by two bytes, i.e. move it to the next integer. This also means that 100 bytes can be used to store 50 integers.

Another possibility of memory allocation is given by the use of the function calloc():

char*calloc();

long *newmem;

newmem = (long *) calloc(100, sizeof(long));

Like malloc() function calloc() returns a pointer to char. You need to use the cast operator if you want to remember a different type. This new function has two arguments, both of which must be unsigned integers. The first argument contains the number of required memory cells. The second argument is the size of each cell in bytes. In our case long

Description of functions

#include void * malloc(size_t size) ; void * calloc(size_t num, size_t size) ;

Purpose

malloc takes as an argument the size of the allocated area in bytes ; returns an untyped pointer (void*) to a memory area of ​​the declared size, or NULL if memory cannot be allocated. The content of the allocated memory area is undefined.

calloc takes as an argument the number of elements and the size of each element in bytes; returns an untyped pointer (void*) to a memory area of ​​the declared size, or NULL if memory cannot be allocated. The element values ​​are set to zero. malloc works faster than calloc, due to the lack of a function to zero the allocated memory.

Function parameters

malloc

  • size- size of allocated memory area

calloc

  • num- number of distributed elements
  • size- the size of each element

Return value

The functions return an untyped (void*) pointer to a memory area if successful, or NULL otherwise.

Typical usage errors

  • The memory remains “occupied” even if no pointer in the program refers to it (the free() function is used to free the memory). The accumulation of "lost" memory areas leads to gradual degradation of the system. Errors associated with non-freeing of occupied areas of memory are called memory leaks. memory leaks).
  • If the amount of data being processed is larger than the amount of allocated memory, other areas of dynamic memory may be corrupted. Such errors are called buffer overflow errors. buffer overflow).
  • If the pointer to the allocated memory area continues to be used after freeing, then an exception may occur when accessing a "no longer existing" block of dynamic memory (eng. exception), program crash, corruption of other data, or nothing happens (depending on the type of operating system and hardware used).
  • If free() is called more than once for the same memory area, this can corrupt the data of the malloc/free library itself, and lead to unpredictable behavior at arbitrary times.
  • Unsuccessful organization of a program in which many small amounts of memory are allocated and freed - fragmentation of free memory (“dotted line”) is possible, in which there is a lot of free memory in total, but it is impossible to allocate a large piece.

The exact behavior of functions is described in the ANSI C standard, and is also referenced by the function definition in the POSIX standard.

Examples of using

malloc

Float * dynamic_array = malloc(number_of_elements * sizeof (float ) ) ; if (! dynamic_array) ( )

calloc

Float * dynamic_array = calloc(number_of_elements, sizeof (float ) ) ; if (! dynamic_array) ( /* handle memory allocation error */ } /* ... work with array elements ... */ free(dynamic_array) ; dynamic_array = NULL;

see also

  • stdlib
  • alloca
  • soap malloc
  • soap destroyer

Sources

  • malloc (English) . - Description of the malloc function in the POSIX standard.
  • calloc (English) . - Description of the calloc function in the POSIX standard.

Wikimedia Foundation. 2010 .

See what "Malloc" is in other dictionaries:

    Malloc- est en informatique une fonction de la bibliothèque standard du C permettant d allouer dynamiquement de la mémoire. La libération de la mémoire ainsi réservée s effectue avec la fonction free. Cette fonction est déclarée dans le fichier d en tête ... Wikipédia en Français

    malloc- est en informatique une fonction de la bibliothèque standard de C permettant d allouer dynamiquement de la mémoire. La libération de la mémoire ainsi réservée s effectue avec la fonction free. Cette fonction est declarée dans l en tête

    Malloc- In computing, malloc is a subroutine provided in the C and C++ programming language s standard libraries for performing dynamic memory allocation. Rationale The C programming language manages memory either statically or automatically . Static ... ... Wikipedia

    Malloc- En informática, malloc es una subrutina para el ejercicio de asignación de memoria dinámica en los lenguajes de programación C y C++. Es una abreviatura del inglés Memory Allocation. Forma parte de la biblioteca estándar stdlib.h para ambos… … Wikipedia Español

    malloc- 1. noun A subroutine in the C programming languages ​​standard library for performing dynamic memory allocation. It compares the behavior of nine different mallocs when used with Hummingbird and GNU Emacs dynamic memory activity traces. 2. verb … Wiktionary

    malloc- ● np. cde. LANGC CMDE Contraction de Memory Allocation. Nom d une fonction très importante de la bibliothèque C, car elle permet d attribuer une partie de la mémoire à un processus. Voir aussi calloc. (Dapres) … Dictionnaire d "informatique francophone

    C dynamic memory allocation- C Standard Library Data types Character classification Strings Mathematics File input/output Date/time Localization … Wikipedia

    Pointer (computing)- This article is about the programming data type. For the input interface (for example a computer mouse), see Pointing device. Pointer a pointing to the memory address associated with variable b. Note that in this particular diagram, the computing … Wikipedia

    The significance of the subject of the article is called into question. Please show in the article the significance of its subject by adding evidence of significance to it according to particular significance criteria or, in the event that private significance criteria for ... ... Wikipedia

    Dangling pointer- Dangling pointers and wild pointers in computer programming are pointers that do not point to a valid object of the appropriate type. These are special cases of memory safety violations. Dangling Pointer Dangling pointers arise when an object is… … Wikipedia


#include void *malloc(size_t size);

Description


Returns a pointer to the first byte of the memory area that was allocated from the heap


The malloc() function returns a pointer to the first byte of a memory area of ​​size size that was allocated from the heap. If there is not enough memory to satisfy the request, a null pointer is returned. It is important to always make sure that the return value is not a null pointer. Attempting to use a null pointer usually results in a complete system crash.

If you are writing 16-bit programs for the 8086 family of processors (such as the 80486 or Pentium), then your compiler probably provides additional memory allocation functions that take into account the segmented memory model used by these processors when running in 16-bit mode. For example, these can be functions that allocate FAR heap memory (which is outside the standard data segment). These functions can assign pointers to memory that is larger than one segment and deallocate that memory.

Computer