Memory allocation: Difference between revisions

From Rosetta Code
Content added Content deleted
m (omit from <- omit)
(Added some Java...maybe someone else could add more)
Line 112: Line 112:
( addr ) free throw
( addr ) free throw
</lang>
</lang>
=={{header|Java}}==
You don't get much control over memory in Java, but here's what you can do:
<lang java>//All of these objects will be deallocated automatically once the program leaves
//their scope and there are no more pointers to the objects
Object foo = new Object(); //Allocate an Object and a reference to it
int[] fooArray = new int[size]; //Allocate all spaces in an array and a reference to it
int x = 0; //Allocate an integer and set its value to 0
</lang>
There is no real destructor in Java as there is in C++, but there is the <tt>finalize</tt> method. From the Java 6 JavaDocs:


''The general contract of finalize is that it is invoked if and when the JavaTM virtual machine has determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, except as a result of an action taken by the finalization of some other object or class which is ready to be finalized. The finalize method may take any action, including making this object available again to other threads; the usual purpose of finalize, however, is to perform cleanup actions before the object is irrevocably discarded. For example, the finalize method for an object that represents an input/output connection might perform explicit I/O transactions to break the connection before the object is permanently discarded.''
<lang java>public class Blah{
//...other methods/data members...
protected void finalize() throws Throwable{
//Finalization code here
}
//...other methods/data members...
}</lang>
==Oberon-2==
==Oberon-2==
'''TODO:'''
'''TODO:'''

Revision as of 18:51, 27 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>

Java

You don't get much control over memory in Java, but here's what you can do: <lang java>//All of these objects will be deallocated automatically once the program leaves //their scope and there are no more pointers to the objects Object foo = new Object(); //Allocate an Object and a reference to it int[] fooArray = new int[size]; //Allocate all spaces in an array and a reference to it int x = 0; //Allocate an integer and set its value to 0 </lang> There is no real destructor in Java as there is in C++, but there is the finalize method. From the Java 6 JavaDocs:

The general contract of finalize is that it is invoked if and when the JavaTM virtual machine has determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, except as a result of an action taken by the finalization of some other object or class which is ready to be finalized. The finalize method may take any action, including making this object available again to other threads; the usual purpose of finalize, however, is to perform cleanup actions before the object is irrevocably discarded. For example, the finalize method for an object that represents an input/output connection might perform explicit I/O transactions to break the connection before the object is permanently discarded. <lang java>public class Blah{

  //...other methods/data members...
  protected void finalize() throws Throwable{
     //Finalization code here
  }
  //...other methods/data members...

}</lang>

Oberon-2

TODO:

Python

Python has the array module: This module defines an object type which can compactly represent an array of basic values: characters, integers, floating point numbers. Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained. The type is specified at object creation time by using a type code, which is a single character. The following type codes are defined:

Type code C Type Python Type Minimum size in bytes
'c' char character 1
'b' signed char int 1
'B' unsigned char int 1
'u' Py_UNICODE Unicode character 2
'h' signed short int 2
'H' unsigned short int 2
'i' signed int int 2
'I' unsigned int long 2
'l' signed long int 4
'L' unsigned long long 4
'f' float float 4
'd' double float 8

The actual representation of values is determined by the machine architecture (strictly speaking, by the C implementation). The actual size can be accessed through the <a title="itemsize" class="reference external" href="../c-api/buffer.html#itemsize">itemsize</a> attribute. The values stored for 'L' and 'I' items will be represented as Python long integers when retrieved, because Python’s plain integer type cannot represent the full range of C’s unsigned (long) integers.

Example <lang python>>>> from array import array >>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \u2641'), ('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])] >>> for typecode, initializer in argslist: a = array(typecode, initializer) print a del a


array('l') array('c', 'hello world') array('u', u'hello \u2641') array('l', [1, 2, 3, 4, 5]) array('d', [1.0, 2.0, 3.1400000000000001]) >>> </lang>