Dynamic Allocation – C/C++ Language

shape
shape
shape
shape
shape
shape
shape
shape

There are three ways to reserve memory space for
the storage of information:

Use of global variables – the placeholder exists as long as
the program is running.
Use of local variables – the placeholder only exists
while the function that declared the variable is being
executed.
Reserve a memory space dynamically: request the
system, at runtime, a space of one
certain size.

malloc() // função básica para alocar memória.

The malloc function:

 

  • It receives as a parameter the number of bytes you want to allocate.
  • Returns the starting address of the allocated memory area.

Dynamic allocation of an integer vector with 10 elements, example:

int *v;
v = malloc (10*4);

If the allocation is successful, ‘v’ will store the starting address of a continuous area of memory sufficient to store 10 integer values.

The sizeof(type) operator returns the number of bytes that a
type occupies in memory.

v = malloc(10*sizeof(int));

Schematic example of what happens in memory:

If there is not enough free space to make the allocation,
the malloc function returns a null address (NULL).

Releasing dynamically allocated space is done by using the ‘free()’ function, which takes the pointer to the memory to be freed as a parameter.

free(v)

OBS:

  • We should only pass the free function a memory address that has been dynamically allocated.

 

  • Once the allocated memory space has been freed, it can no longer be accessed.
  • As long as the free function is not used, the dynamically allocated space will remain valid even after the end of a given function.

Leave a Reply

Your email address will not be published. Required fields are marked *

Latest news

Latest news directly from our blog.