malloc
malloc
malloc
malloc
malloc-Related Functions
printf
sysconf
pathconf
@dircategory GNU libraries @direntry * Libc: (libc). C library.
@shorttitlepage The GNU C Library Reference Manual The GNU C Library
Reference Manual
Sandra Loosemore with Richard M. Stallman, Roland McGrath, Andrew Oram, and Ulrich Drepper
Edition 0.07 DRAFT
last updated 4 Oct 1996
for version 2.00 Beta Copyright (C) 1993, '94, '95, '96, '97 Free Software Foundation, Inc.
Published by the Free Software Foundation
59 Temple Place -- Suite 330,
Boston, MA 02111-1307 USA
Printed copies are available for $50 each.
ISBN 1-882114-53-1
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided also that the section entitled "GNU Library General Public License" is included exactly as in the original, and provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.
Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that the text of the translation of the section entitled "GNU Library General Public License" must be approved for accuracy by the Foundation.
The C language provides no built-in facilities for performing such common operations as input/output, memory management, string manipulation, and the like. Instead, these facilities are defined in a standard library, which you compile and link with your programs.
The GNU C library, described in this document, defines all of the library functions that are specified by the ISO C standard, as well as additional features specific to POSIX and other derivatives of the Unix operating system, and extensions specific to the GNU system.
The purpose of this manual is to tell you how to use the facilities of the GNU library. We have mentioned which features belong to which standards to help you identify things that are potentially nonportable to other systems. But the emphasis in this manual is not on strict portability.
This manual is written with the assumption that you are at least somewhat familiar with the C programming language and basic programming concepts. Specifically, familiarity with ISO standard C (see section ISO C), rather than "traditional" pre-ISO C dialects, is assumed.
The GNU C library includes several header files, each of which provides definitions and declarations for a group of related facilities; this information is used by the C compiler when processing your program. For example, the header file `stdio.h' declares facilities for performing input and output, and the header file `string.h' declares string processing utilities. The organization of this manual generally follows the same division as the header files.
If you are reading this manual for the first time, you should read all of the introductory material and skim the remaining chapters. There are a lot of functions in the GNU C library and it's not realistic to expect that you will be able to remember exactly how to use each and every one of them. It's more important to become generally familiar with the kinds of facilities that the library provides, so that when you are writing your programs you can recognize when to make use of library functions, and where in this manual you can find more specific information about them.
This section discusses the various standards and other sources that the GNU C library is based upon. These sources include the ISO C and POSIX standards, and the System V and Berkeley Unix implementations.
The primary focus of this manual is to tell you how to make effective use of the GNU library facilities. But if you are concerned about making your programs compatible with these standards, or portable to operating systems other than GNU, this can affect how you use the library. This section gives you an overview of these standards, so that you will know what they are when they are mentioned in other parts of the manual.
See section Summary of Library Facilities, for an alphabetical list of the functions and other symbols provided by the library. This list also states which standards each function or symbol comes from.
The GNU C library is compatible with the C standard adopted by the American National Standards Institute (ANSI): American National Standard X3.159-1989---"ANSI C" and later by the International Standardization Organization (ISO): ISO/IEC 9899:1990, "Programming languages--C". We here refer to the standard as ISO C since this is the more general standard in respect of ratification. The header files and library facilities that make up the GNU library are a superset of those specified by the ISO C standard.
If you are concerned about strict adherence to the ISO C standard, you should use the `-ansi' option when you compile your programs with the GNU C compiler. This tells the compiler to define only ISO standard features from the library header files, unless you explicitly ask for additional features. See section Feature Test Macros, for information on how to do this.
Being able to restrict the library to include only ISO C features is important because ISO C puts limitations on what names can be defined by the library implementation, and the GNU extensions don't fit these limitations. See section Reserved Names, for more information about these restrictions.
This manual does not attempt to give you complete details on the differences between ISO C and older dialects. It gives advice on how to write programs to work portably under multiple C dialects, but does not aim for completeness.
The GNU library is also compatible with the IEEE POSIX family of standards, known more formally as the Portable Operating System Interface for Computer Environments. POSIX is derived mostly from various versions of the Unix operating system.
The library facilities specified by the POSIX standards are a superset of those required by ISO C; POSIX specifies additional features for ISO C functions, as well as specifying new additional functions. In general, the additional requirements and functionality defined by the POSIX standards are aimed at providing lower-level support for a particular kind of operating system environment, rather than general programming language support which can run in many diverse operating system environments.
The GNU C library implements all of the functions specified in IEEE Std 1003.1-1990, the POSIX System Application Program Interface, commonly referred to as POSIX.1. The primary extensions to the ISO C facilities specified by this standard include file system interface primitives (see section File System Interface), device-specific terminal control functions (see section Low-Level Terminal Interface), and process control functions (see section Processes).
Some facilities from IEEE Std 1003.2-1992, the POSIX Shell and Utilities standard (POSIX.2) are also implemented in the GNU library. These include utilities for dealing with regular expressions and other pattern matching facilities (see section Pattern Matching).
The GNU C library defines facilities from some versions of Unix which are not formally standardized, specifically from the 4.2 BSD, 4.3 BSD, and 4.4 BSD Unix systems (also known as Berkeley Unix) and from SunOS (a popular 4.2 BSD derivative that includes some Unix System V functionality). These systems support most of the ISO C and POSIX facilities, and 4.4 BSD and newer releases of SunOS in fact support them all.
The BSD facilities include symbolic links (see section Symbolic Links), the
select function (see section Waiting for Input or Output), the BSD signal
functions (see section BSD Signal Handling), and sockets (see section Sockets).
The System V Interface Description (SVID) is a document describing the AT&T Unix System V operating system. It is to some extent a superset of the POSIX standard (see section POSIX (The Portable Operating System Interface)).
The GNU C library defines some of the facilities required by the SVID that are not also required by the ISO C or POSIX standards, for compatibility with System V Unix and other Unix systems (such as SunOS) which include these facilities. However, many of the more obscure and less generally useful facilities required by the SVID are not included. (In fact, Unix System V itself does not provide them all.)
This section describes some of the practical issues involved in using the GNU C library.
Libraries for use by C programs really consist of two parts: header files that define types and macros and declare variables and functions; and the actual library or archive that contains the definitions of the variables and functions.
(Recall that in C, a declaration merely provides information that a function or variable exists and gives its type. For a function declaration, information about the types of its arguments might be provided as well. The purpose of declarations is to allow the compiler to correctly process references to the declared variables and functions. A definition, on the other hand, actually allocates storage for a variable or says what a function does.)
In order to use the facilities in the GNU C library, you should be sure that your program source files include the appropriate header files. This is so that the compiler has declarations of these facilities available and can correctly process references to them. Once your program has been compiled, the linker resolves these references to the actual definitions provided in the archive file.
Header files are included into a program source file by the `#include' preprocessor directive. The C language supports two forms of this directive; the first,
#include "header"
is typically used to include a header file header that you write yourself; this would contain definitions and declarations describing the interfaces between the different parts of your particular application. By contrast,
#include <file.h>
is typically used to include a header file `file.h' that contains definitions and declarations for a standard library. This file would normally be installed in a standard place by your system administrator. You should use this second form for the C library header files.
Typically, `#include' directives are placed at the top of the C source file, before any other code. If you begin your source files with some comments explaining what the code in the file does (a good idea), put the `#include' directives immediately afterwards, following the feature test macro definition (see section Feature Test Macros).
For more information about the use of header files and `#include' directives, see section `Header Files' in The GNU C Preprocessor Manual.
The GNU C library provides several header files, each of which contains the type and macro definitions and variable and function declarations for a group of related facilities. This means that your programs may need to include several header files, depending on exactly which facilities you are using.
Some library header files include other library header files automatically. However, as a matter of programming style, you should not rely on this; it is better to explicitly include all the header files required for the library facilities you are using. The GNU C library header files have been written in such a way that it doesn't matter if a header file is accidentally included more than once; including a header file a second time has no effect. Likewise, if your program needs to include multiple header files, the order in which they are included doesn't matter.
Compatibility Note: Inclusion of standard header files in any order and any number of times works in any ISO C implementation. However, this has traditionally not been the case in many older C implementations.
Strictly speaking, you don't have to include a header file to use a function it declares; you could declare the function explicitly yourself, according to the specifications in this manual. But it is usually better to include the header file because it may define types and macros that are not otherwise available and because it may define more efficient macro replacements for some functions. It is also a sure way to have the correct declaration.
If we describe something as a function in this manual, it may have a macro definition as well. This normally has no effect on how your program runs--the macro definition does the same thing as the function would. In particular, macro equivalents for library functions evaluate arguments exactly once, in the same way that a function call would. The main reason for these macro definitions is that sometimes they can produce an inline expansion that is considerably faster than an actual function call.
Taking the address of a library function works even if it is also defined as a macro. This is because, in this context, the name of the function isn't followed by the left parenthesis that is syntactically necessary to recognize a macro call.
You might occasionally want to avoid using the macro definition of a function--perhaps to make your program easier to debug. There are two ways you can do this:
For example, suppose the header file `stdlib.h' declares a function
named abs with
extern int abs (int);
and also provides a macro definition for abs. Then, in:
#include <stdlib.h>
int f (int *i) { return (abs (++*i)); }
the reference to abs might refer to either a macro or a function.
On the other hand, in each of the following examples the reference is
to a function and not a macro.
#include <stdlib.h>
int g (int *i) { return ((abs)(++*i)); }
#undef abs
int h (int *i) { return (abs (++*i)); }
Since macro definitions that double for a function behave in exactly the same way as the actual function version, there is usually no need for any of these methods. In fact, removing macro definitions usually just makes your program slower.
The names of all library types, macros, variables and functions that come from the ISO C standard are reserved unconditionally; your program may not redefine these names. All other library names are reserved if your program explicitly includes the header file that defines or declares them. There are several reasons for these restrictions:
exit to do something completely different from
what the standard exit function does, for example. Preventing
this situation helps to make your programs easier to understand and
contributes to modularity and maintainability.
In addition to the names documented in this manual, reserved names include all external identifiers (global functions and variables) that begin with an underscore (`_') and all identifiers regardless of use that begin with either two underscores or an underscore followed by a capital letter are reserved names. This is so that the library and header files can define functions, variables, and macros for internal purposes without risk of conflict with names in user programs.
Some additional classes of identifier names are reserved for future extensions to the C language or the POSIX.1 environment. While using these names for your own purposes right now might not cause a problem, they do raise the possibility of conflict with future versions of the C or POSIX standards, so you should avoid these names.
float and long double arguments,
respectively.
In addition, some individual header files reserve names beyond those that they actually define. You only need to worry about these restrictions if your program includes that particular header file.
The exact set of features available when you compile a source file is controlled by which feature test macros you define.
If you compile your programs using `gcc -ansi', you get only the ISO C library features, unless you explicitly request additional features by defining one or more of the feature macros. See section `GNU CC Command Options' in The GNU CC Manual, for more information about GCC options.
You should define these macros by using `#define' preprocessor
directives at the top of your source code files. These directives
must come before any #include of a system header file. It
is best to make them the very first thing in the file, preceded only by
comments. You could also use the `-D' option to GCC, but it's
better if you make the source files indicate their own meaning in a
self-contained way.
1, then the
functionality from the POSIX.1 standard (IEEE Standard 1003.1) is made
available. If you define this macro with a value of 2, then both
the functionality from the POSIX.1 standard and the functionality from
the POSIX.2 standard (IEEE Standard 1003.2) are made available. This is
in addition to the ISO C facilities.
Some of the features derived from 4.3 BSD Unix conflict with the corresponding features specified by the POSIX.1 standard. If this macro is defined, the 4.3 BSD definitions take precedence over the POSIX definitions.
Due to the nature of some of the conflicts between 4.3 BSD and POSIX.1,
you need to use a special BSD compatibility library when linking
programs compiled for BSD compatibility. This is because some functions
must be defined in two different ways, one of them in the normal C
library, and one of them in the compatibility library. If your program
defines _BSD_SOURCE, you must give the option `-lbsd-compat'
to the compiler or linker when linking the program, to tell it to find
functions in this special compatibility library before looking for them in
the normal C library.
_POSIX_SOURCE and
_POSIX_C_SOURCE are automatically defined.
As the unification of all Unices, functionality only available in BSD and SVID is also included.
If the macro _XOPEN_SOURCE_EXTENDED is also defined, even more
functionality is available. The extra functions will make all functions
available which are necessary for the X/Open Unix brand.
If you want to get the full effect of _GNU_SOURCE but make the
BSD definitions take precedence over the POSIX definitions, use this
sequence of definitions:
#define _GNU_SOURCE #define _BSD_SOURCE #define _SVID_SOURCE
Note that if you do this, you must link your program with the BSD compatibility library by passing the `-lbsd-compat' option to the compiler or linker. Note: If you forget to do this, you may get very strange errors at run time.
Unlike on some other systems no special version of the C library must be used for linking. There is only one version but while compiling this it must have been specified to compile as thread safe.
We recommend you use _GNU_SOURCE in new programs. If you don't
specify the `-ansi' option to GCC and don't define any of these
macros explicitly, the effect is the same as defining
_POSIX_C_SOURCE to 2 and _POSIX_SOURCE,
_SVID_SOURCE, and _BSD_SOURCE to 1.
When you define a feature test macro to request a larger class of features,
it is harmless to define in addition a feature test macro for a subset of
those features. For example, if you define _POSIX_C_SOURCE, then
defining _POSIX_SOURCE as well has no effect. Likewise, if you
define _GNU_SOURCE, then defining either _POSIX_SOURCE or
_POSIX_C_SOURCE or _SVID_SOURCE as well has no effect.
Note, however, that the features of _BSD_SOURCE are not a subset of
any of the other feature test macros supported. This is because it defines
BSD features that take precedence over the POSIX features that are
requested by the other macros. For this reason, defining
_BSD_SOURCE in addition to the other feature test macros does have
an effect: it causes the BSD features to take priority over the conflicting
POSIX features.
Here is an overview of the contents of the remaining chapters of this manual.
sizeof
operator and the symbolic constant NULL, how to write functions
accepting variable numbers of arguments, and constants describing the
ranges and other properties of the numerical types. There is also a simple
debugging mechanism which allows you to put assertions in your code, and
have diagnostic messages printed if the tests fail.
isspace) and functions for
performing case conversion.
FILE * objects). These are the normal C library functions
from `stdio.h'.
char data type.
setjmp and
longjmp functions. These functions provide a facility for
goto-like jumps which can jump from one function to another.
If you already know the name of the facility you are interested in, you can look it up in section Summary of Library Facilities. This gives you a summary of its syntax and a pointer to where you can find a more detailed description. This appendix is particularly useful if you just want to verify the order and type of arguments to a function, for example. It also tells you what standard or system each function, variable, or macro is derived from.
Many functions in the GNU C library detect and report error conditions, and sometimes your programs need to check for these error conditions. For example, when you open an input file, you should verify that the file was actually opened correctly, and print an error message or take other appropriate action if the call to the library function failed.
This chapter describes how the error reporting facility works. Your program should include the header file `errno.h' to use this facility.
Most library functions return a special value to indicate that they have
failed. The special value is typically -1, a null pointer, or a
constant such as EOF that is defined for that purpose. But this
return value tells you only that an error has occurred. To find out
what kind of error it was, you need to look at the error code stored in the
variable errno. This variable is declared in the header file
`errno.h'.
errno contains the system error number. You can
change the value of errno.
Since errno is declared volatile, it might be changed
asynchronously by a signal handler; see section Defining Signal Handlers.
However, a properly written signal handler saves and restores the value
of errno, so you generally do not need to worry about this
possibility except when writing signal handlers.
The initial value of errno at program startup is zero. Many
library functions are guaranteed to set it to certain nonzero values
when they encounter certain kinds of errors. These error conditions are
listed for each function. These functions do not change errno
when they succeed; thus, the value of errno after a successful
call is not necessarily zero, and you should not use errno to
determine whether a call failed. The proper way to do that is
documented for each function. If the call the failed, you can
examine errno.
Many library functions can set errno to a nonzero value as a
result of calling other library functions which might fail. You should
assume that any library function might alter errno when the
function returns an error.
Portability Note: ISO C specifies errno as a
"modifiable lvalue" rather than as a variable, permitting it to be
implemented as a macro. For example, its expansion might involve a
function call, like *_errno (). In fact, that is what it is
on the GNU system itself. The GNU library, on non-GNU systems, does
whatever is right for the particular system.
There are a few library functions, like sqrt and atan,
that return a perfectly legitimate value in case of an error, but also
set errno. For these functions, if you want to check to see
whether an error occurred, the recommended method is to set errno
to zero before calling the function, and then check its value afterward.
All the error codes have symbolic names; they are macros defined in `errno.h'. The names start with `E' and an upper-case letter or digit; you should consider names of this form to be reserved names. See section Reserved Names.
The error code values are all positive integers and are all distinct,
with one exception: EWOULDBLOCK and EAGAIN are the same.
Since the values are distinct, you can use them as labels in a
switch statement; just don't use both EWOULDBLOCK and
EAGAIN. Your program should not make any other assumptions about
the specific values of these symbolic constants.
The value of errno doesn't necessarily have to correspond to any
of these macros, since some library functions might return other error
codes of their own for other situations. The only values that are
guaranteed to be meaningful for a particular library function are the
ones that this manual lists for that function.
On non-GNU systems, almost any system call can return EFAULT if
it is given an invalid pointer as an argument. Since this could only
happen as a result of a bug in your program, and since it will not
happen on the GNU system, we have saved space by not mentioning
EFAULT in the descriptions of individual functions.
In some Unix systems, many system calls can also return EFAULT if
given as an argument a pointer into the stack, and the kernel for some
obscure reason fails in its attempt to extend the stack. If this ever
happens, you should probably try using statically or dynamically
allocated memory instead of stack memory on that system.
The error code macros are defined in the header file `errno.h'. All of them expand into integer constant values. Some of these error codes can't occur on the GNU system, but they can occur using the GNU library on other systems.
You can choose to have functions resume after a signal that is handled,
rather than failing with EINTR; see section Primitives Interrupted by Signals.
exec functions (see section Executing a File) occupy too much memory space. This condition never arises in the
GNU system.
exec functions; see section Executing a File.
link (see section Hard Links) but
also when you rename a file with rename (see section Renaming Files).
In BSD and GNU, the number of open files is controlled by a resource
limit that can usually be increased. If you get this error, you might
want to increase the RLIMIT_NOFILE limit or make it unlimited;
see section Limiting Resource Usage.
rename can cause this error if the file being renamed already has
as many links as it can take (see section Renaming Files).
SIGPIPE signal; this signal terminates the program if not handled
or blocked. Thus, your program will never actually see EPIPE
unless it has handled or blocked SIGPIPE.
EWOULDBLOCK is another name for EAGAIN;
they are always the same in the GNU C library.
This error can happen in a few different situations:
select to find out
when the operation will be possible; see section Waiting for Input or Output.
Portability Note: In many older Unix systems, this condition
was indicated by EWOULDBLOCK, which was a distinct error code
different from EAGAIN. To make your program portable, you should
check for both codes and treat them the same.
fork
can return this error. It indicates that the shortage is expected to
pass, so your program can try the call again later and it may succeed.
It is probably a good idea to delay for a few seconds before trying it
again, to allow time for other processes to release scarce resources.
Such shortages are usually fairly serious and affect the whole system,
so usually an interactive program should report the error to the user
and return to its command loop.
EAGAIN (above).
The values are always the same, on every operating system.
C libraries in many older Unix systems have EWOULDBLOCK as a
separate error code.
connect; see section Making a Connection) never return
EAGAIN. Instead, they return EINPROGRESS to indicate that
the operation has begun and will take some time. Attempts to manipulate
the object before the call completes return EALREADY. You can
use the select function to find out when the pending operation
has completed; see section Waiting for Input or Output.
ENOMEM; you may get one or the
other from network operations.
EDESTADDRREQ instead.
connect.
PATH_MAX; see section Limits on File System Capacity) or host name too long (in gethostname or
sethostname; see section Host Identification).
fork. See section Limiting Resource Usage, for details on
the RLIMIT_NPROC limit.
On some systems chmod returns this error if you try to set the
sticky bit on a non-directory file; see section Assigning File Permissions.
term protocol return
this error for certain operations when the caller is not in the
foreground process group of the terminal. Users do not usually see this
error because functions such as read and write translate
it into a SIGTTIN or SIGTTOU signal. See section Job Control,
for information on process groups and these signals.
The following error codes are defined by the Linux/i386 kernel. They are not yet documented.
The library has functions and variables designed to make it easy for
your program to report informative error messages in the customary
format about the failure of a library call. The functions
strerror and perror give you the standard error message
for a given error code; the variable
program_invocation_short_name gives you convenient access to the
name of the program that encountered the error.
strerror function maps the error code (see section Checking for Errors) specified by the errnum argument to a descriptive error
message string. The return value is a pointer to this string.
The value errnum normally comes from the variable errno.
You should not modify the string returned by strerror. Also, if
you make subsequent calls to strerror, the string might be
overwritten. (But it's guaranteed that no library function ever calls
strerror behind your back.)
The function strerror is declared in `string.h'.
strerror_r function works like strerror but instead of
returning the error message in a statically allocated buffer shared by
all threads in the process, it writes the message string in the user
supplied buffer starting at buf with the length of n bytes.
At most n characters are written (including the NUL byte) so it is up to the user to select the buffer large enough.
This function should always be used in multi-threaded programs since
there is no way to guarantee the string returned by strerror
really belongs to the last call of the current thread.
This function strerror_r is a GNU extension and it is declared in
`string.h'.
stderr;
see section Standard Streams.
If you call perror with a message that is either a null
pointer or an empty string, perror just prints the error message
corresponding to errno, adding a trailing newline.
If you supply a non-null message argument, then perror
prefixes its output with this string. It adds a colon and a space
character to separate the message from the error string corresponding
to errno.
The function perror is declared in `stdio.h'.
strerror and perror produce the exact same message for any
given error code; the precise text varies from system to system. On the
GNU system, the messages are fairly short; there are no multi-line
messages or embedded newlines. Each error message begins with a capital
letter and does not include any terminating punctuation.
Compatibility Note: The strerror function is a new
feature of ISO C. Many older C systems do not support this function
yet.
Many programs that don't read input from the terminal are designed to
exit if any system call fails. By convention, the error message from
such a program should start with the program's name, sans directories.
You can find that name in the variable
program_invocation_short_name; the full file name is stored the
variable program_invocation_name:
argv[0]. Note
that this is not necessarily a useful file name; often it contains no
directory names. See section Program Arguments.
program_invocation_name minus
everything up to the last slash, if any.)
The library initialization code sets up both of these variables before
calling main.
Portability Note: These two variables are GNU extensions. If
you want your program to work with non-GNU libraries, you must save the
value of argv[0] in main, and then strip off the directory
names yourself. We added these extensions to make it possible to write
self-contained error-reporting subroutines that require no explicit
cooperation from main.
Here is an example showing how to handle failure to open a file
correctly. The function open_sesame tries to open the named file
for reading and returns a stream if successful. The fopen
library function returns a null pointer if it couldn't open the file for
some reason. In that situation, open_sesame constructs an
appropriate error message using the strerror function, and
terminates the program. If we were going to make some other library
calls before passing the error code to strerror, we'd have to
save it in a local variable instead, because those other library
functions might overwrite errno in the meantime.
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
FILE *
open_sesame (char *name)
{
FILE *stream;
errno = 0;
stream = fopen (name, "r");
if (stream == NULL)
{
fprintf (stderr, "%s: Couldn't open file %s; %s\n",
program_invocation_short_name, name, strerror (errno));
exit (EXIT_FAILURE);
}
else
return stream;
}
The GNU system provides several methods for allocating memory space under explicit program control. They vary in generality and in efficiency.
malloc facility allows fully general dynamic allocation.
See section Unconstrained Allocation.
malloc but more
efficient and convenient for stacklike allocation. See section Obstacks.
alloca lets you allocate storage dynamically that
will be freed automatically. See section Automatic Storage with Variable Size.
Dynamic memory allocation is a technique in which programs determine as they are running where to store some information. You need dynamic allocation when the number of memory blocks you need, or how long you continue to need them, depends on the data you are working on.
For example, you may need a block to store a line read from an input file; since there is no limit to how long a line can be, you must allocate the storage dynamically and make it dynamically larger as you read more of the line.
Or, you may need a block for each record or each definition in the input data; since you can't know in advance how many there will be, you must allocate a new block for each record or definition as you read it.
When you use dynamic allocation, the allocation of a block of memory is an action that the program requests explicitly. You call a function or macro when you want to allocate space, and specify the size with an argument. If you want to free the space, you do so by calling another function or macro. You can do these things whenever you want, as often as you want.
The C language supports two kinds of memory allocation through the variables in C programs:
Dynamic allocation is not supported by C variables; there is no storage class "dynamic", and there can never be a C variable whose value is stored in dynamically allocated space. The only way to refer to dynamically allocated space is through a pointer. Because it is less convenient, and because the actual process of dynamic allocation requires more computation time, programmers generally use dynamic allocation only when neither static nor automatic allocation will serve.
For example, if you want to allocate dynamically some space to hold a
struct foobar, you cannot declare a variable of type struct
foobar whose contents are the dynamically allocated space. But you can
declare a variable of pointer type struct foobar * and assign it the
address of the space. Then you can use the operators `*' and
`->' on this pointer variable to refer to the contents of the space:
{
struct foobar *ptr
= (struct foobar *) malloc (sizeof (struct foobar));
ptr->name = x;
ptr->next = current_foobar;
current_foobar = ptr;
}
The most general dynamic allocation facility is malloc. It
allows you to allocate blocks of memory of any size at any time, make
them bigger or smaller at any time, and free the blocks individually at
any time (or never).
To allocate a block of memory, call malloc. The prototype for
this function is in `stdlib.h'.
The contents of the block are undefined; you must initialize it yourself
(or use calloc instead; see section Allocating Cleared Space).
Normally you would cast the value as a pointer to the kind of object
that you want to store in the block. Here we show an example of doing
so, and of initializing the space with zeros using the library function
memset (see section Copying and Concatenation):
struct foo *ptr; ... ptr = (struct foo *) malloc (sizeof (struct foo)); if (ptr == 0) abort (); memset (ptr, 0, sizeof (struct foo));
You can store the result of malloc into any pointer variable
without a cast, because ISO C automatically converts the type
void * to another type of pointer when necessary. But the cast
is necessary in contexts other than assignment operators or if you might
want your code to run in traditional C.
Remember that when allocating space for a string, the argument to
malloc must be one plus the length of the string. This is
because a string is terminated with a null character that doesn't count
in the "length" of the string but does need space. For example:
char *ptr; ... ptr = (char *) malloc (length + 1);
See section Representation of Strings, for more information about this.
malloc
If no more space is available, malloc returns a null pointer.
You should check the value of every call to malloc. It is
useful to write a subroutine that calls malloc and reports an
error if the value is a null pointer, returning only if the value is
nonzero. This function is conventionally called xmalloc. Here
it is:
void *
xmalloc (size_t size)
{
register void *value = malloc (size);
if (value == 0)
fatal ("virtual memory exhausted");
return value;
}
Here is a real example of using malloc (by way of xmalloc).
The function savestring will copy a sequence of characters into
a newly allocated null-terminated string:
char *
savestring (const char *ptr, size_t len)
{
register char *value = (char *) xmalloc (len + 1);
memcpy (value, ptr, len);
value[len] = '\0';
return value;
}
The block that malloc gives you is guaranteed to be aligned so
that it can hold any type of data. In the GNU system, the address is
always a multiple of eight on most systems, and a multiple of 16 on
64-bit systems. Only rarely is any higher boundary (such as a page
boundary) necessary; for those cases, use memalign or
valloc (see section Allocating Aligned Memory Blocks).
Note that the memory located after the end of the block is likely to be
in use for something else; perhaps a block already allocated by another
call to malloc. If you attempt to treat the block as longer than
you asked for it to be, you are liable to destroy the data that
malloc uses to keep track of its blocks, or you may destroy the
contents of another block. If you have already allocated a block and
discover you want it to be bigger, use realloc (see section Changing the Size of a Block).
malloc
When you no longer need a block that you got with malloc, use the
function free to make the block available to be allocated again.
The prototype for this function is in `stdlib.h'.
free function deallocates the block of storage pointed at
by ptr.
free. It's provided for
backward compatibility with SunOS; you should use free instead.
Freeing a block alters the contents of the block. Do not expect to find any data (such as a pointer to the next block in a chain of blocks) in the block after freeing it. Copy whatever you need out of the block before freeing it! Here is an example of the proper way to free all the blocks in a chain, and the strings that they point to:
struct chain
{
struct chain *next;
char *name;
}
void
free_chain (struct chain *chain)
{
while (chain != 0)
{
struct chain *next = chain->next;
free (chain->name);
free (chain);
chain = next;
}
}
Occasionally, free can actually return memory to the operating
system and make the process smaller. Usually, all it can do is allow a
later call to malloc to reuse the space. In the meantime, the
space remains in your program as part of a free-list used internally by
malloc.
There is no point in freeing blocks at the end of a program, because all of the program's space is given back to the system when the process terminates.
Often you do not know for certain how big a block you will ultimately need at the time you must begin to use the block. For example, the block might be a buffer that you use to hold a line being read from a file; no matter how long you make the buffer initially, you may encounter a line that is longer.
You can make the block longer by calling realloc. This function
is declared in `stdlib.h'.
realloc function changes the size of the block whose address is
ptr to be newsize.
Since the space after the end of the block may be in use, realloc
may find it necessary to copy the block to a new address where more free
space is available. The value of realloc is the new address of the
block. If the block needs to be moved, realloc copies the old
contents.
If you pass a null pointer for ptr, realloc behaves just
like `malloc (newsize)'. This can be convenient, but beware
that older implementations (before ISO C) may not support this
behavior, and will probably crash when realloc is passed a null
pointer.
Like malloc, realloc may return a null pointer if no
memory space is available to make the block bigger. When this happens,
the original block is untouched; it has not been modified or relocated.
In most cases it makes no difference what happens to the original block
when realloc fails, because the application program cannot continue
when it is out of memory, and the only thing to do is to give a fatal error
message. Often it is convenient to write and use a subroutine,
conventionally called xrealloc, that takes care of the error message
as xmalloc does for malloc:
void *
xrealloc (void *ptr, size_t size)
{
register void *value = realloc (ptr, size);
if (value == 0)
fatal ("Virtual memory exhausted");
return value;
}
You can also use realloc to make a block smaller. The reason you
is needed.
In several allocation implementations, making a block smaller sometimes
necessitates copying it, so it can fail if no other space is available.
If the new size you specify is the same as the old size, realloc
is guaranteed to change nothing and return the same address that you gave.
The function calloc allocates memory and clears it to zero. It
is declared in `stdlib.h'.