C Memory Functions

malloc(long size): void*

Allocates a contiguous memory area with the given size in bytes. This can be used to create arrays of dynamic size. This function is slow, so it is recommended to use it for allocating memory areas in the initial run.  If there is not enough memory, 0 is returned.

realloc(void* ptr, long size): void*

Reallocates the memory area given by ptr. It must have been previously allocated by malloc. Returns a pointer to the new memory area. The old memory area is freed, the old content is copied over to the new area. This function is slow. If there is not enough memory, the old memory area is not freed and 0 is returned.

zalloc(long size): void* (temporary)

Like malloc, but returns a pointer to a temporary memory area that is initialized to zero and preserved until the next zalloc call. This function is fast, and the memory area needs not be freed. Use this for allocating a single temporary array inside functions.

Parameters:

size - Size of the allocated memory area, in bytes.

Returns:

void* pointer to the allocated memory area, or 0 when the allocation failed.
 

free(void* ptr)

Releases a contiguous memory area that was allocated with malloc.

Parameter:

ptr - void* pointer to the allocated memory area.
 

memcpy(void* dest, void* src, long size)

Copies size bytes from src to dest. Can be used to copy a whole struct or array with a single function.

Parameters:

dest - Target address.
src - Source address.
size - Number of bytes to copy.
 

memset(void* dest, int c, long size)

Sets the first size characters of dest to the character c. Can be used to initialize a whole struct or array to zero.

Parameters:

dest - Target address.
c - value to copy, 0..255.
size - Number of bytes to copy.
 

memcmp(void* buffer1, void* buffer2, long size)

Compares buffer1 with buffer2. Returns 0 when both are identical, otherwise nonzero.

Parameters:

buffer1 - First buffer.
buffer2 - Second buffer.
size - Number of bytes to compare.
 

Remarks:

Example (see also http):

var calculate_something()
{
  var *Buffer = zalloc(100*sizeof(var));
  int i;
  for(i=1; i<100; i++)
    buffer[i] = buffer[i-1]+1;
  return Buffer[99]; // last element
}

See also:

sizeof, memory

► latest version online