Memory allocation: Difference between revisions

From Rosetta Code
Content added Content deleted
m (→‎{{header|C}}: forgot an example)
m (→‎{{header|C}}: static added)
Line 4: Line 4:
=={{header|C}}==
=={{header|C}}==


The functions <tt>malloc</tt>, <tt>calloc</tt> and <tt>realloc</tt> take memory from the heap. This memory ''should'' be released with <tt>free</tt>.
The functions <tt>malloc</tt>, <tt>calloc</tt> and <tt>realloc</tt> take memory from the heap. This memory ''should'' be released with <tt>free</tt> and it's suitable for sharing memory among threads.


<lang c>#include <stdlib.h>
<lang c>#include <stdlib.h>
Line 58: Line 58:
}</lang>
}</lang>


Variables declared outside any block and function live as long as the program lives (their scope is global) and the memory for them is statically given (e.g. through a .bss block)
Variables declared outside any block and function or inside a function but prepended with the attribute <tt>static</tt> live as long as the program lives and the memory for them is statically given (e.g. through a .bss block).


<lang c>/* this is global */
<lang c>/* this is global */
Line 65: Line 65:
int funcB()
int funcB()
{
{
static int ints[NMEMB]; /* this is "static", i.e. the memory "survive" even
return integers[0];
when the function exits, but the symbol's scope is local */
return integers[0] + ints[0];
}
}



Revision as of 17:45, 26 May 2009

Task
Memory allocation
You are encouraged to solve this task according to the task description, using any language you may know.

Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e. heap, stack, shared, foreign) if applicable.

C

The functions malloc, calloc and realloc take memory from the heap. This memory should be released with free and it's suitable for sharing memory among threads.

<lang c>#include <stdlib.h>

/* size of "members", in bytes */

  1. define SIZEOF_MEMB (sizeof(int))
  2. define NMEMB 100

int main() {

 int *ints = (int *)malloc(SIZEOF_MEMB*NMEMB);
 /* realloc can be used to increase or decrease an already
    allocated memory (same as malloc if ints is NULL) */
 ints = (int *)realloc(ints, sizeof(int)*(NMEMB+1));
 /* calloc set the memory to 0s */
 int *int2 = (int *)calloc(NMEMB, SIZEOF_MEMB);
 /* all use the same free */
 free(ints); free(int2);
 return 0;

}</lang>

Variables declared inside a block (a function or inside a function) take room from the stack and survive until the "block" is in execution (and their scope is local).

<lang c>int func() {

 int ints[NMEMB]; /* it resembles calloc ... */
 int *int2;       /* here the only thing allocated on the stack is a pointer */
 char intstack[SIZEOF_MEMB*NMEMB]; /* to show resemblance to malloc */
 int2 = (int *)intstack;           /* but this is educative, do not do so unless... */
 {
   char *pointers_to_char[NMEMB];
   /* use pointers_to_char */
   pointers_to_char[0] = "educative";
 } /* outside the block, the variable "disappears" */
 /* here we can use ints, int2, intstack vars, which are not seen elsewhere of course */
 return 0;

}</lang>

Works with: gcc

The libc provided by gcc (and present on other "systems" too) has the alloca function which allows to ask for memory on the stack explicitly; the memory is deallocated when the function that asked for the memory ends (it is, in practice, the same behaviour for automatic variables). The usage is the same as for functions like malloc

<lang c>#include <alloca.h> int *funcA() {

 int *ints = (int *)alloca(SIZEOF_MEMB*NMEMB);
 ints[0] = 0;                                  /* use it */
 return ints; /* BUT THIS IS WRONG! It is not like malloc: the memory
                 does not "survive"! */

}</lang>

Variables declared outside any block and function or inside a function but prepended with the attribute static live as long as the program lives and the memory for them is statically given (e.g. through a .bss block).

<lang c>/* this is global */ int integers[NMEMB]; /* should be initialized with 0s */

int funcB() {

 static int ints[NMEMB]; /* this is "static", i.e. the memory "survive" even
                            when the function exits, but the symbol's scope is local */ 
 return integers[0] + ints[0];

}

void funcC(int a) {

 integers[0] = a;

}</lang>

C++

TODO: new and delete/delete[]

Forth

Forth has two main bulk memory areas, each with their own word sets and semantics for allocation and deallocation.

Dictionary

All Forth implementations have a stack-like memory space called the dictionary. It is used both for code definitions and data structures. <lang forth> unused . \ memory available for use in dictionary here . \ current dictionary memory pointer

mem, ( addr len -- ) here over allot swap move ;
s, ( str len -- ) here over char+ allot place align ; \ built-in on some forths
," [char] " parse s, ;

variable num create array 60 cells allot create struct 0 , 10 , char A c, ," string" unused . here . </lang>

Dictionary space is meant for static code definitions and supporting data structures, so it is not as easy to deallocate from it. For ad-hoc allocations without intervening definitions, you may give a negative value to ALLOT to reclaim the space. You may also lay down a named MARKER to reclaim the space used by all subsequent definitions. <lang forth> marker foo

temp ... ;

create dummy 300 allot -150 allot \ trim the size of dummy by 150 bytes foo \ removes foo, temp, and dummy from the list of definitions </lang>

Heap

Most Forth implementations also give access to a larger random-access memory heap. <lang forth>

 4096 allocate throw  ( addr )
 dup 4096 erase
 ( addr ) free throw

</lang>

Oberon-2

TODO:

Pascal

TODO: