CMPSC
311,
Introduction to Systems Programming
Storage Allocation
Reading
- CP:AMA
- First, skim through Sec. 17.5, to see where we're headed,
and refresh your thinking about boxes-and-arrows diagrams.
- Ch. 11, Pointers [review]
- Ch. 12, Pointers and Arrays, esp. Sec. 1-3 [review]
- Ch. 16, Structures, Unions, and Enumerations, esp. Sec. 1-3
- Ch. 17, Advanced Use of Pointers, esp. Sec. 1-5 and the
Q&A
- CS:APP
- Sec. 3.9, Heterogeneous Data Structures, esp. Sec. 3.9.1,
3.9.3 [review]
- Sec. 3.10, Putting it Together: Understanding Pointers
[review]
- Sec. 7.9, Loading Executable Object Files [review]
- Sec. 9.9, Dynamic Memory Allocation, intro, Sec. 9.9.1,
9.9.2, 9.9.3
- We will cover the remaining parts of Sec. 9.9 later.
- Sec. 9.11, Common Memory-Related Bugs in C Programs
[review]
- C:ARM, Sec. 11.1,
size_t; Sec. 16.1, malloc,
etc.
- APUE, Sec. 7.8, Memory Allocation
- important advice if you tend to write buggy programs
- C Standard, Posix Standard, and man pages at the end
In the C Standard,
#include <stddef.h>
typedef ... size_t;
- the unsigned integral type of the result of the
sizeof
operator
- typically
unsigned long int
#include <stdint.h>
#define SIZE_MAX ...
- C99 only, the largest value of a
size_t
variable or constant
#include <stdlib.h>
void *malloc(size_t size);
void free(void *ptr);
void *calloc(size_t count, size_t size);
void *realloc(void *ptr, size_t size);
Also on Solaris,
void *memalign(size_t alignment, size_t size);
void *valloc(size_t size);
#include <alloca.h>
void *alloca(size_t size);
#include <malloc.h>
int mallopt(int cmd, int value);
struct mallinfo mallinfo(void);
Also on Mac OS X,
void * valloc(size_t size);
void * reallocf(void *ptr, size_t size);
size_t malloc_size(void *ptr);
size_t malloc_good_size(size_t size);
Also on Linux,
#include <malloc.h>
void *valloc(size_t size); // obsolete
void *memalign(size_t boundary, size_t size); //
obsolete
#include <alloca.h>
void *alloca(size_t size); // discouraged
In the POSIX Standard,
#include <stdlib.h>
int posix_memalign(void **memptr, size_t alignment,
size_t size);
Typical usage - a
dynamically-allocated array (1)
If the array can be treated as a local variable, and you have C99 or
C++, then this will probably be sufficient -
int number_of_elements = some positive value;
int foo[number_of_elements]; /* local only */
... use foo[i] for i between 0 and number_of_elements
- 1
The array will be stored on the runtime stack, since it is a
local variable.
- The elements of
foo[] are uninitialized, unless
you explicitly initialize them.
int foo[number_of_elements] = { 0 };
for (int i = 0; i < number_of_elements;
i++)
foo[i] = 0;
- You must be right the first time, about the number of
elements.
- You do not need to use all the elements, but you can't make
the array larger.
- Vastly overestimating the number of elements wastes storage.
- In some cases, the system places limits on the stack size,
making this method impractical.
- What happens if
number_of_elements is too
large?
- The array will be deallocated automatically when you leave the
scope of its definition.
Typical usage - a
dynamically-allocated array (2)
If the array does not need to be treated as a local variable, or if
you only have C89, then follow this style -
int *bar = NULL; /*
global or local */
int number_of_elements = some
positive value;
bar = (int *) malloc(number_of_elements * sizeof(int));
if (bar == NULL)
{ allocation failed
}
... use bar[i] for i between 0 and number_of_elements
- 1
The array will be stored on the runtime heap, and it must be
explicitly deallocated by calling free().
- Of course, the entire address space will be deallocated when
the process exits.
- C doesn't have garbage collection, so don't lose the pointer!
IMPORTANT! Always verify that malloc()
succeeded.
if (bar == NULL)
{
fprintf(stderr,
"%s: array bar[], malloc() failed: %s\n",
program_name,
strerror(errno));
// Now what?
}
IMPORTANT! malloc()
does not initialize the memory it allocates.
IMPORTANT! Do not
change bar.
free(bar); //
deallocation
Now it is a good idea to
change bar.
bar = NULL;
Consider these options:
bar =
calloc(number_of_elements, sizeof(int));
bar = realloc(bar, larger_number_of_elements
* sizeof(int));
Exercise (this is important). Draw the boxes-and-arrows
diagrams for foo and bar.
Typical usage - dynamically-allocated structs
and arrays of structs
For one instance of a struct,
struct foo {
int data; // just for an example
...
};
struct foo foo_instance;
... use foo_instance.data
struct foo *fooptr = (struct foo *) malloc(sizeof(struct
foo));
if (fooptr == NULL)
{ allocation
failed }
... use fooptr->data
IMPORTANT! Always verify that malloc()
succeeded.
if (fooptr == NULL)
{
fprintf(stderr,
"%s: struct foo, malloc() failed: %s\n",
program_name,
strerror(errno));
// Now what?
}
For an array of structs,
int number_of_elements = some positive value;
struct foo *fooarray = (struct foo *) malloc(number_of_elements
* sizeof(struct foo));
if (fooarray == NULL)
{ allocation
failed }
... use fooarray, for example as a function argument
... use *fooarray to obtain the value of fooarray[0]
... use fooarray[i] for i between 0
and number_of_elements - 1
... use fooarray[i].data
IMPORTANT! Always
verify that malloc() succeeded.
IMPORTANT! malloc()
does not initialize the memory it allocates.
IMPORTANT! Do not
change fooptr or fooarray.
free(fooptr);
free(fooarray);
Now it is a good idea to
change fooptr
and fooarray.
fooptr = NULL;
fooarray = NULL;
Mistakes often occur when you do not understand these ideas:
- Defining a pointer does not define something for it to point
to.
- Memory allocators can fail. Always check the return
value.
malloc() does not initialize the allocated
memory.
calloc() initializes the allocated memory to 0.
realloc() only initializes from the previous
allocation.
- Do not go outside the bounds of the allocated block of memory.
- The argument to
free() must be a return value
from malloc(), calloc() or realloc().
- Do not call
free() twice with the same argument.
- This is the "double free" bug.
- Do not use a pointer to allocated memory after you have freed
it.
- This is the "dangling pointer" bug.
- If you copy a pointer to allocated memory, follow the rules
for all copies of the pointer.
A simple partial Linked-List implementation, version 1
struct node {
struct node *next;
int data; // generic contents
};
struct list {
struct node *head;
struct node *tail;
};
Stop now to draw the
pictures - the data structures, an empty list, a singleton list, a
two-element list, etc.
struct node *node_allocate(void)
{
return malloc(sizeof(struct node));
}
void node_deallocate(struct node *node)
{
free(node);
}
struct list *list_allocate(void)
{
return malloc(sizeof(struct list));
}
void list_deallocate(struct list *list)
{
free(list);
}
What's wrong with this version?
A simple partial Linked-List implementation, version 2
struct node {
struct node *next;
int data; // generic contents
};
struct list {
struct node *head;
struct node *tail;
};
struct node *node_allocate(void)
{
struct node *p = malloc(sizeof(struct node));
if (p == NULL) { print a
message and exit }
p->next = NULL;
p->data = 0; // or something else appropriate
return p;
}
void node_deallocate(struct node *node)
{
free(node);
}
struct list *list_allocate(void)
{
struct list *p = malloc(sizeof(struct list));
if (p == NULL) { print a message and exit }
p->head = NULL;
p->tail = NULL;
return p;
}
void list_deallocate(struct list *list)
{
free(list);
}
What's wrong with this version?
void list_append(struct list *list, struct node *node)
{
if (list == NULL) { print
a message and exit }
if (node == NULL) { print
a message and exit }
struct node *p = list->tail;
p->next = node;
list->tail = node;
}
What's wrong with this version?
struct node *list_search(struct list *list, int data_key)
{
if (list == NULL) { print a message and exit }
for (struct node *p = list->head; p != NULL; p =
p->next)
{
if (p->data == data_key) break;
}
return p;
}
What's wrong with this version?
For a correct and reasonably complete implementation of a
singly-linked list, see the c2html
program.
Example - What is the current working directory?
#include <unistd.h>
// absolute pathname of the
current working directory
char *getcwd(char *buf, size_t size);
// the maximum length of a
pathname is a configurable limit;
// use name = _PC_PATH_MAX
to obtain PATH_MAX
long int pathconf(const char
*path, int name);
First version - choose the buffer size by guesswork
char buffer[4096];
char *cwd = getcwd(buffer, sizeof(buffer));
if (cwd == NULL)
{ printf("current working directory = (not
found) %s\n", strerror(errno)); }
else
{ printf("current working directory = %s\n",
cwd); }
Second version - choose the buffer size by trial-and-error
size_t size;
long int path_max =
pathconf(".", _PC_PATH_MAX);
if (path_max ==
-1) //
the system does not specify PATH_MAX
{ size =
1024; }
else if (path_max >
10240) // PATH_MAX is really large
{ size =
10240; }
else
{ size =
path_max; }
char *buf =
malloc(size);
char *cwd = NULL;
while (1)
{
if (buf == NULL) break;
cwd = getcwd(buf, size);
if (cwd == NULL && errno == ERANGE)
{
size
*= 2; buf = realloc(buf, size); continue; }
else
{
break;
}
}
if (cwd == NULL)
{
printf("current working directory = (not found) %s\n",
strerror(errno)); }
else
{
printf("current working directory = %s\n", cwd); }
free(buf);
Some discussion of alternative designs for getcwd() appears in the
Posix Standard.
From the C Standard
7.20.3 Memory management functions
The order and contiguity of storage allocated by successive calls to
the calloc, malloc, and realloc functions is
unspecified. The pointer returned if the allocation succeeds is
suitably aligned so that it may be assigned to a pointer to any type
of object and then used to access such an object or an array of such
objects in the space allocated (until the space is explicitly
deallocated). The lifetime of an allocated object extends from
the allocation until the deallocation. Each such allocation
shall yield a pointer to an object disjoint from any other
object. The pointer returned points to the start (lowest byte
address) of the allocated space. If the space cannot be
allocated, a null pointer is returned. If the size of the
space requested is zero, the behavior is implementation-defined:
either a null pointer is returned, or the behavior is as if the size
were some nonzero value, except that the returned pointer shall not
be used to access an object.
7.20.3.1 The calloc function
Synopsis
#include <stdlib.h>
void *calloc(size_t nmemb, size_t size);
Description
The calloc function allocates space for an array
of nmemb objects,
each of whose size is size.
The space is initialized to all bits zero. [footnote - Note
that this need not be the same as the representation of
floating-point zero or a null pointer constant.]
Returns
The calloc function returns either a null pointer
or a pointer to the allocated space.
7.20.3.2 The free function
Synopsis
#include <stdlib.h>
void free(void *ptr);
Description
The free function causes the space pointed to by
ptr to be
deallocated, that is, made available for further allocation.
If ptr is a null
pointer, no action occurs. Otherwise, if the argument does
not match a pointer earlier returned by the calloc, malloc, or realloc function, or if
the space has been deallocated by a call to free or realloc, the behavior is
undefined.
Returns
The free function returns no value.
7.20.3.3 The malloc function
Synopsis
#include <stdlib.h>
void *malloc(size_t size);
Description
The malloc function allocates space for an object
whose size is specified by size
and whose value is indeterminate.
Returns
The malloc function returns either a null pointer
or a pointer to the allocated space.
7.20.3.4 The realloc function
Synopsis
#include <stdlib.h>
void *realloc(void *ptr, size_t size);
Description
The realloc function deallocates the old object
pointed to by ptr
and returns a pointer to a new object that has the size specified
by size.
The
contents
of
the
new
object
shall
be the same as that of the old object prior to deallocation, up to
the lesser of the new and old sizes. Any bytes in the new
object beyond the size of the old object have indeterminate
values.
If ptr is a null
pointer, the realloc
function behaves like the malloc
function for the specified size. Otherwise, if ptr does not match a
pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been
deallocated by a call to the free or realloc function, the behavior is
undefined. If memory for the new object cannot be allocated,
the old object is not deallocated and its value is unchanged.
Returns
The realloc function returns a pointer to the new
object (which may have the same value as a pointer to the old
object), or a null pointer if the new object could not be
allocated.
From the Posix Standard (via Linux man -a malloc)
MALLOC(P)
MALLOC(P)
NAME
malloc - a memory allocator
SYNOPSIS
#include <stdlib.h>
void *malloc(size_t size);
DESCRIPTION
The malloc()
function shall allocate unused space for an object whose
size in bytes is specified by size and whose value is unspecified.
The
order
and
contiguity
of
storage
allocated
by successive calls to
malloc()
is unspecified. The pointer returned if the allocation suc-
ceeds
shall
be
suitably
aligned
so
that
it may be assigned to a
pointer
to
any
type
of
object
and
then used to access such an object
in
the
space
allocated
(until
the
space
is explicitly freed or reallo-
cated).
Each
such
allocation
shall
yield
a
pointer to an object dis-
joint
from
any
other
object.
The
pointer
returned points to the start
(lowest
byte
address)
of
the
allocated
space.
If the space cannot be
allocated,
a
null
pointer
shall
be
returned.
If the size of the space
requested
is
0,
the
behavior
is
implementation-defined:
the
value
returned
shall
be
either
a
null
pointer
or a unique pointer.
RETURN
VALUE
Upon successful completion with size not equal to 0, malloc() shall
return
a
pointer
to
the
allocated
space.
If size is 0,
either a null
pointer
or
a
unique
pointer
that
can
be successfully passed to free()
shall
be
returned.
Otherwise,
it
shall
return
a null pointer and
set errno to
indicate the error.
ERRORS
The malloc()
function shall fail if:
ENOMEM Insufficient storage space is available.
The following sections
are informative.
EXAMPLES
None.
APPLICATION
USAGE
None.
RATIONALE
None.
FUTURE
DIRECTIONS
None.
SEE ALSO
calloc() , free() ,
realloc()
, the Base Definitions volume of
IEEE Std 1003.1-2001, <stdlib.h>
COPYRIGHT
Portions
of
this
text
are
reprinted
and
reproduced in electronic form
from
IEEE
Std
1003.1,
2003
Edition,
Standard
for Information Technol-
ogy
--
Portable
Operating
System
Interface
(POSIX),
The
Open Group
Base
Specifications
Issue
6,
Copyright
(C)
2001-2003
by the Institute
of
Electrical
and
Electronics
Engineers,
Inc
and
The Open Group. In
the
event
of
any
discrepancy
between
this
version and the original
IEEE
and
The
Open
Group
Standard,
the
original IEEE and The Open Group
Standard
is
the
referee
document.
The
original
Standard
can be
obtained online at http://www.opengroup.org/unix/online.html .
POSIX
2003
MALLOC(P)
MALLOC(3)
Linux Programmer’s
Manual
MALLOC(3)
NAME
calloc,
malloc,
free,
realloc
-
Allocate
and
free dynamic memory
SYNOPSIS
#include <stdlib.h>
void *calloc(size_t nmemb, size_t size);
void *malloc(size_t size);
void free(void *ptr);
void *realloc(void *ptr, size_t size);
DESCRIPTION
calloc()
allocates
memory
for
an
array
of
nmemb elements of size bytes
each
and
returns
a
pointer
to
the
allocated memory. The memory is set
to zero.
malloc()
allocates
size
bytes
and
returns
a
pointer to the allocated
memory. The memory is not cleared.
free()
frees
the
memory
space
pointed
to
by ptr, which must have been
returned
by
a
previous
call
to
malloc(),
calloc() or realloc(). Oth-
erwise,
or
if
free(ptr)
has
already
been
called before, undefined
behaviour
occurs.
If
ptr
is
NULL,
no
operation is performed.
realloc()
changes
the
size
of
the
memory
block pointed to by ptr to
size
bytes.
The
contents
will
be
unchanged
to the minimum of the old
and
new
sizes;
newly
allocated
memory
will
be uninitialized. If ptr
is
NULL,
the
call
is
equivalent
to
malloc(size); if size is equal to
zero,
the
call
is
equivalent
to
free(ptr).
Unless
ptr is NULL, it
must
have
been
returned
by
an
earlier
call to malloc(), calloc() or
realloc().
RETURN VALUE
For
calloc()
and
malloc(),
the
value
returned
is
a pointer to the
allocated
memory,
which
is
suitably
aligned
for
any kind of variable,
or NULL if the request fails.
free() returns no value.
realloc()
returns
a
pointer
to
the
newly
allocated memory, which is
suitably
aligned
for
any
kind
of
variable
and may be different from
ptr,
or
NULL
if
the
request
fails.
If size was equal to 0, either NULL
or
a
pointer
suitable
to
be
passed
to free() is returned. If real-
loc()
fails
the
original
block
is
left
untouched - it is not freed or
moved.
CONFORMING TO
ANSI-C
SEE ALSO
brk(2), posix_memalign(3)
NOTES
The
Unix98
standard
requires
malloc(),
calloc(),
and
realloc() to set
errno
to
ENOMEM
upon
failure.
Glibc
assumes
that this is done (and the
glibc
versions
of
these
routines
do
this);
if you use a private malloc
implementation
that
does
not
set
errno,
then
certain library routines
may
fail
without
having
a
reason
in
errno.
Crashes
in
malloc(),
free()
or
realloc()
are
almost always related to
heap
corruption,
such
as
overflowing
an
allocated
chunk or freeing the
same pointer twice.
Recent
versions
of
Linux
libc
(later
than
5.4.23) and GNU libc (2.x)
include
a
malloc
implementation
which
is
tunable
via environment vari-
ables.
When
MALLOC_CHECK_
is
set,
a
special
(less efficient) imple-
mentation
is
used
which
is
designed
to
be tolerant against simple
errors,
such
as
double
calls
of
free()
with the same argument, or
overruns
of
a
single
byte
(off-by-one
bugs).
Not all such errors can
be
protected
against,
however,
and
memory
leaks
can result. If MAL-
LOC_CHECK_
is
set
to
0,
any
detected
heap
corruption is silently
ignored;
if
set
to
1,
a
diagnostic
is printed on stderr; if set to 2,
abort()
is
called
immediately.
This
can
be
useful because otherwise a
crash
may
happen
much
later,
and
the
true cause for the problem is
then very hard to track down.
BUGS
By
default,
Linux
follows
an
optimistic
memory
allocation
strategy.
This
means
that
when
malloc()
returns
non-NULL
there is no guarantee
that
the
memory
really
is
available.
This
is a really bad bug. In
case
it
turns
out
that
the
system
is out of memory, one or more pro-
cesses
will
be
killed
by
the
infamous
OOM killer. In case Linux is
employed
under
circumstances
where
it
would
be
less desirable to sud-
denly
lose
some
randomly
picked
processes,
and
moreover
the kernel
version
is
sufficiently
recent,
one
can
switch
off this overcommitting
behavior using a command like
# echo 2 > /proc/sys/vm/overcommit_memory
See also the kernel Documentation
directory, files vm/overcommit-
accounting and sysctl/vm.txt.
GNU
1993-04-04
MALLOC(3)
From Mac OS X
MALLOC(3)
BSD Library Functions
Manual
MALLOC(3)
NAME
calloc, free, malloc, realloc, reallocf, valloc -- memory
allocation
SYNOPSIS
#include <stdlib.h>
void
*
calloc(size_t count, size_t size);
void
free(void *ptr);
void
*
malloc(size_t size);
void
*
realloc(void *ptr, size_t size);
void
*
reallocf(void *ptr, size_t size);
void
*
valloc(size_t size);
DESCRIPTION
The
malloc(), calloc(), valloc(), realloc(), and reallocf() functions
allocate memory. The allocated memory is aligned such that
it can be
used
for any data type, including AltiVec- and SSE-related types.
The
free() function frees allocations that were created via the
preceding
allocation functions.
The
malloc() function allocates size bytes of memory and returns a
pointer to the allocated memory.
The
calloc() function contiguously allocates enough space for count
objects that are size bytes of memory each and returns a pointer
to the
allocated memory. The allocated memory is filled with bytes
of value
zero.
The
valloc() function allocates size bytes of memory and returns a
pointer to the allocated memory. The allocated memory is
aligned on a
page
boundary.
The
realloc() function tries to change the size of the allocation
pointed
to by
ptr to size, and returns ptr. If there is not enough room to
enlarge the memory allocation pointed to by ptr, realloc() creates
a new
allocation, copies as much of the old data pointed to by ptr as
will fit
to
the new allocation, frees the old allocation, and returns a
pointer to
the
allocated memory. If ptr is NULL, realloc() is identical to
a call
to
malloc() for size bytes. If size is zero and ptr is not
NULL, a new,
minimum sized object is allocated and the original object is
freed.
The
reallocf() function is identical to the realloc() function, except
that
it will free the passed pointer when the requested memory cannot
be
allocated. This is a FreeBSD specific API designed to ease
the problems
with
traditional coding styles for realloc causing memory leaks in
libraries.
The
free() function deallocates the memory allocation pointed to by
ptr.
RETURN VALUES
If
successful, calloc(), malloc(), realloc(), reallocf(), and
valloc()
functions return a pointer to allocated memory. If there is
an error,
they
return a NULL pointer and set errno to ENOMEM.
For
realloc(), the input pointer is still valid if reallocation
failed.
For
reallocf(), the input pointer will have been freed if reallocation
failed.
The
free() function does not return a value.
DEBUGGING ALLOCATION ERRORS
A
number of facilities are provided to aid in debugging allocation
errors
in
applications. These facilities are primarily controlled via
environ-
ment
variables. The recognized environment variables and their
meanings
are
documented below.
ENVIRONMENT
The
following environment variables change the behavior of the alloca-
tion-related functions.
MallocLogFile
<f>
Create/append messages to the given file
path
<f>
instead
of
writing
to
the
standard
error.
MallocGuardEdges
If
set,
add
a
guard
page
before
and after
each large block.
MallocDoNotProtectPrelude If set, do not add a
guard page before large
blocks, even if the MallocGuardEdges envi-
ronment variable is set.
MallocDoNotProtectPostlude If set, do not add a guard
page after large
blocks, even if the MallocGuardEdges envi-
ronment variable is set.
MallocStackLogging
If
set,
record
all
stacks,
so
that
tools
like leaks can be used.
MallocStackLoggingNoCompact If set, record all stacks in a
manner that
is compatible with the malloc_history pro-
gram.
MallocPreScribble
If
set,
fill
memory
that
has
been
allocated
with 0xaa bytes. This increases the likeli-
hood that a program making assumptions about
the contents of freshly allocated memory
will fail.
MallocScribble
If
set,
fill
memory
that
has
been
deallo-
cated with 0x55 bytes. This increases the
likelihood
that
a
program
will
fail
due
to
accessing memory that is no longer allo-
cated.
MallocCheckHeapStart <s> If set,
specifies the number of allocations
gram.
MallocPreScribble
If
set,
fill
memory
that
has
been
allocated
with 0xaa bytes. This increases the likeli-
hood that a program making assumptions about
the contents of freshly allocated memory
will fail.
MallocScribble
If
set,
fill
memory
that
has
been
deallo-
cated with 0x55 bytes. This increases the
likelihood
that
a
program
will
fail
due
to
accessing memory that is no longer allo-
cated.
MallocCheckHeapStart <s> If set,
specifies the number of allocations
<s> to wait before begining periodic heap
checks every <n> as specified by
MallocCheckHeapEach. If
MallocCheckHeapStart is set but
MallocCheckHeapEach is not specified, the
default check repetition is 1000.
MallocCheckHeapEach <n> If
set, run a consistency check on the heap
every <n> operations. MallocCheckHeapEach
is only meaningful if MallocCheckHeapStart
is also set.
MallocCheckHeapSleep <t> Sets the
number of seconds to sleep (waiting
for a debugger to attach) when
MallocCheckHeapStart is set and a heap cor-
ruption is detected. The default is 100
seconds.
Setting
this
to
zero
means
not
to
sleep
at
all.
Setting
this
to
a
negative
number
means
to
sleep
(for
the
positive
num-
ber
of
seconds)
only
the
very
first
time a
heap corruption is detected.
MallocCheckHeapAbort <b> When
MallocCheckHeapStart is set and this is
set
to
a
non-zero
value,
causes
abort(3)
to
be
called
if
a
heap
corruption
is
detected,
instead of any sleeping.
MallocErrorAbort
If
set,
causes
abort(3)
to
be
called
if an
error was encountered in malloc(3) or
free(3)
,
such
as
a
calling
free(3)
on a
pointer previously freed.
MallocHelp
If
set,
print
a
list
of
environment
vari-
ables
that
are
paid
heed
to
by
the alloca-
tion-related functions, along with short
descriptions. The list should correspond to
this documentation.
DIAGNOSTIC MESSAGES
SEE ALSO
leaks(1), malloc_history(1), abort(3), malloc_size(3)
/Developer/ADC
Reference Library/releasenotes/DeveloperTools/MallocOptions.html
BSD
May 23,
2006
BSD
From Solaris
Standard C Library
Functions
malloc(3C)
NAME
malloc, calloc, free, memalign, realloc, valloc,
alloca -
memory allocator
SYNOPSIS
#include <stdlib.h>
void
*malloc(size_t size);
void
*calloc(size_t nelem, size_t elsize);
void
free(void *ptr);
void
*memalign(size_t alignment, size_t size);
void
*realloc(void *ptr, size_t size);
void
*valloc(size_t size);
#include <alloca.h>
void
*alloca(size_t size);
The malloc() and free() functions
provide a simple,
general-purpose memory allocation package.
The malloc()
function returns a pointer to a block of at least size bytes
suitably aligned for any use. If the space assigned by mal-
loc()
is overrun, the results are undefined.
The
argument to free() is a pointer to a block
previously
allocated by malloc(), calloc(), or realloc(). After free()
is
executed, this space is made available for further allo-
cation by the application, though not returned to the
sys-
tem.
Memory is returned to the system only upon termination
of the application. If ptr is a null
pointer, no action
occurs. If a random number is passed to free(), the results
are
undefined.
The
calloc() function allocates space for an array of nelem
elements of size elsize. The space is initialized to zeros.
The
memalign() function allocates size bytes on a specified
alignment boundary and returns a pointer to the
allocated
block. The value of the returned address is guaranteed to be
an even multiple of alignment. The value of alignment
must
be a
power of two and must be greater than or equal to the
size
of a word.
The
realloc() function changes the size of the block pointed
to by
ptr to size bytes and returns a pointer to the (possi-
bly
moved) block. The contents will be unchanged up to the
lesser of the new and old sizes. If
the new size of the
block
requires movement of the block, the space for the pre-
vious instantiation of the block is freed. If the new
size
is
larger, the contents of the newly allocated
portion of
the
block are unspecified. If ptr is NULL, realloc() behaves
like
malloc() for the specified size. If size is 0 and ptr
is
not a null pointer, the space pointed to is freed.
The
valloc() function has the same
effect as malloc(),
except that the allocated memory will be aligned to a multi-
ple
of the value returned by sysconf(_SC_PAGESIZE).
The
alloca() function allocates size bytes of space in the
stack frame of the caller, and
returns a pointer to the
allocated block. This temporary space is automatically freed
when the caller returns. If the allocated block
is beyond
the
current stack limit, the resulting behavior
is unde-
fined.
Upon
successful completion, each of the allocation functions
returns a pointer to space suitably aligned (after possible
pointer coercion) for storage of any type of object.
If there is no available
memory, malloc(), realloc(),
memalign(), valloc(), and calloc() return a null
pointer.
When
realloc() is called with size > 0 and returns NULL, the
block pointed to by ptr is left intact. If size,
nelem, or
elsize is 0, either a null pointer or a unique pointer that
can
be passed to free() is returned.
If
malloc(), calloc(), or realloc() returns unsuccessfully,
errno
will be set to indicate the error. The free() function
does
not set errno.
The
malloc(), calloc(), and realloc() functions will
fail
if:
ENOMEM
The physical limits of the
system are
exceeded
by
size
bytes
of
memory
which
can-
not be allocated.
EAGAIN There
is not enough memory available to
allocate size bytes of memory;
but the
application could try again later.
USAGE
Portable applications should avoid using valloc() but should
instead use malloc() or mmap(2). On
systems with a large
page
size, the number of successful
valloc() operations
might
be 0.
These
default memory allocation routines are safe for use in
multithreaded applications but are not scalable. Concurrent
accesses by multiple threads are single-threaded through the
use of a single lock. Multithreaded applications that
make
heavy
use of dynamic memory allocation should be linked with
allocation libraries designed for concurrent access, such as
libumem(3LIB) or libmtmalloc(3LIB). Applications that
want
to avoid using heap allocations (with brk(2)) can do
so by
using
either libumem or libmapmalloc(3LIB). The allocation
libraries libmalloc(3LIB) and libbsdmalloc(3LIB) are avail-
able
for special needs.
Comparative features of the various allocation libraries can
be
found in the umem_alloc(3MALLOC) manual page.
See
attributes(5) for descriptions of the following attri-
butes:
____________________________________________________________
| ATTRIBUTE
TYPE
| ATTRIBUTE
VALUE |
|_____________________________|_____________________________|
| Interface
Stability | See
below.
|
|_____________________________|_____________________________|
|
MT-Level
|
Safe
|
|_____________________________|_____________________________|
The
malloc(), calloc(), free(), realloc(), valloc()
func-
tions are Standard. The memalign() and alloca()
functions
are
Stable.
brk(2), getrlimit(2), libbsdmalloc(3LIB),
libmalloc(3LIB),
libmapmalloc(3LIB),
libmtmalloc(3LIB), libumem(3LIB),
umem_alloc(3MALLOC), watchmalloc(3MALLOC), attributes(5)
WARNINGS
Undefined results will occur if the size
requested for a
block of memory exceeds the maximum
size of a process's
heap,
which can be obtained with getrlimit(2)
The
alloca() function is machine-, compiler-, and
most of
all,
system-dependent. Its use is strongly discouraged.
SunOS
5.10 Last
change: 21 Mar
2005
From Solaris
Memory Allocation Library
Functions
malloc(3MALLOC)
NAME
malloc, free, realloc, calloc, mallopt, mallinfo
- memory
allocator
SYNOPSIS
cc [
flag ... ] file ... -lmalloc [ library ... ]
#include
<stdlib.h>
void
*malloc(size_t size);
void
free(void *ptr);
void
*realloc(void *ptr, size_t size);
void
*calloc(size_t nelem, size_t elsize);
#include <malloc.h>
int
mallopt(int cmd, int value);
struct mallinfo mallinfo(void);
The
malloc() and free() functions provide a simple general-
purpose memory allocation package.
The
malloc() function returns a pointer to a block
of at
least
size bytes suitably aligned for any use.
The
argument to free() is a pointer to a block
previously
allocated by malloc(). After free() is performed, this space
is
made available for further allocation, and its
contents
have
been destroyed. See mallopt() below for a way to change
this
behavior. If ptr is a null pointer, no action occurs.
Undefined results occur if the space assigned by malloc() is
overrun or if some random number is handed to free().
The
free() function does not set errno.
The
realloc() function changes the size of the block pointed
to by
ptr to size bytes and returns a pointer to the (possi-
bly
moved) block. The contents will be unchanged up to the
lesser of the new and old sizes. If
the new size of the
block
requires movement of the block, the space for the pre-
vious instantiation of the block is freed. If the new
size
is
larger, the contents of the newly allocated
portion of
the
block are unspecified. If ptr is NULL, realloc() behaves
like
malloc() for the specified size. If size is 0 and ptr
is
not a null pointer, the space pointed to is freed.
The
calloc() function allocates space for an array of nelem
elements of size elsize. The space is initialized to zeros.
The
mallopt() function provides for control over the alloca-
tion
algorithm. The available values for cmd are:
M_MXFAST Set maxfast
to value. The algorithm allo-
cates
all
blocks
below
the
size
of
maxfast
in
large
groups
and
then
doles
them
out very
quickly. The default value for maxfast is
24.
M_NLBLKS Set numlblks to
value. The above mentioned
``large groups'' each contain
numlblks
blocks. numlblks must be greater than 0.
The default value for numlblks is 100.
M_GRAIN Set grain
to value. The sizes of all blocks
smaller than maxfast are considered to be
rounded
up
to
the
nearest
multiple
of
grain.
grain
must
be
greater
than
0.
The
default
value
of
grain
is
the
smallest
number
of
bytes
that
will
allow
alignment
of
any
data
type.
Value
will
be
rounded
up
to
a multiple
of the default when grain is set.
M_KEEP
Preserve data in a freed block until the
next malloc(), realloc(), or calloc(). This
option is provided only for compatibility
with
the
old
version
of
malloc(),
and
it is
not recommended.
These
values are defined in the <malloc.h> header.
The
mallopt() function can be called repeatedly, but cannot
be
called after the first small block is allocated.
The
mallinfo() function provides instrumentation describing
space
usage. It returns the mallinfo structure with the fol-
lowing members:
unsigned long arena; /* total space
in arena */
unsigned long ordblks; /* number of ordinary
blocks */
unsigned long smblks; /* number of small
blocks */
unsigned long hblkhd; /* space in holding
block headers */
unsigned long hblks; /* number of
holding blocks */
unsigned long usmblks; /* space in small blocks
in use */
unsigned long fsmblks; /* space in free small
blocks */
unsigned long uordblks; /* space in ordinary blocks in
use */
unsigned long fordblks; /* space in free ordinary
blocks */
unsigned long keepcost; /* space penalty if keep
option */
/* is used */
The
mallinfo structure is defined in the <malloc.h> header.
Each
of the allocation routines returns a pointer to space
suitably aligned (after possible
pointer coercion) for
storage of any type of object.
The
malloc(), realloc(), and calloc() functions
return a
null pointer if there is not enough available memory.
When
realloc() returns NULL, the block pointed to by ptr is left
intact. If size, nelem, or
elsize is 0, either a null
pointer or a unique pointer that can be passed to free() is
returned. If mallopt() is called after any allocation or if
cmd
or value are invalid, a non-zero value is returned. Oth-
erwise, it returns 0.
If
malloc(), calloc(), or realloc() returns unsuccessfully,
errno
is set to indicate the error:
ENOMEM size
bytes of memory exceeds the physical
limits
of
your
system,
and
cannot
be
allo-
cated.
EAGAIN There
is not enough memory available at this
point
in
time
to
allocate
size
bytes
of
memory; but the application could try again
later.
Unlike malloc(3C), this package does not preserve the
con-
tents
of a block when it is freed, unless the M_KEEP option
of
mallopt() is used.
Undocumented features of malloc(3C) have not
been dupli-
cated.
Function prototypes for malloc(), realloc(), calloc(),
and
free() are also defined in the <malloc.h> header for
compa-
tibility with old applications. New
applications should
include <stdlib.h> to access the prototypes for these
func-
tions.
Comparative features of the various allocation libraries can
be
found in the umem_alloc(3MALLOC) manual page.
See
attributes(5) for descriptions of the following attri-
butes:
____________________________________________________________
| ATTRIBUTE
TYPE
| ATTRIBUTE
VALUE |
|_____________________________|_____________________________|
|
MT-Level
|
Safe
|
|_____________________________|_____________________________|
brk(2), bsdmalloc(3MALLOC), libmtmalloc(3LIB),
malloc(3C),
mapmalloc(3MALLOC), mtmalloc(3MALLOC), umem_alloc(3MALLOC),
watchmalloc(3MALLOC), attributes(5)
SunOS
5.10 Last
change: 21 Mar
2005
Last revised, 6 Feb. 2013