C Programming/stdlib.h/Function reference
abort
[edit | edit source]Prototype
[edit | edit source]void abort(void);
Description
[edit | edit source]This function is to stop the program or process abnormally. It is required in the program when wrong condition gets encountered in program execution then to come out of process this function is used.
It deletes buffers and closes all open files before ending the program. The function abort() terminates the current program. Depending on the implementation, the return from the function can indicate a canceled (e.g. you used the signal() function to catch SIGABRT) or failed abort. SIGABRT is sent by the process to itself when it calls the abort libc function, defined in cstdlib. The SIGABRT signal can be caught, but it cannot be blocked; if the signal handler returns then all open streams are closed and flushed and the program terminates (dumping core if appropriate) , then it returns control to host environment.This means that the abort call never returns. Because of this characteristic, it is often used to signal fatal conditions in support libraries, situations where the current operation cannot be completed but the main program can perform cleanup before exiting. It is also used if an assertion fails.
It is one of the thread safe functions from standard c library.i.e. function can be called by different threads without any problem.
abs
[edit | edit source]Prototypes
[edit | edit source]int abs (int i);
long labs (long i);
double fabs (double i);
float fabsf (float i);
long double fabsl (long double i);
Description
[edit | edit source]Many programming languages have functions that calculate absolute values of numbers, either having the name abs or Abs. In languages such as C, it has variants for long integers and floating point numbers called labs and fabs. All the functions take a signed number as a parameter, and returns the absolute value of that number in the same data type.
atexit
[edit | edit source]Prototype
[edit | edit source]int atexit(void (*function)(void));
Description
[edit | edit source]This function registers the given function to be executed at normal process termination, either via exit or via return from the program's main function.
The atexit
function takes, as argument, the reference of the function to be registered for call back. Functions so registered are called in the reverse order of their registration; no arguments are passed.
The atexit
function is standardized by the POSIX specification.
The function returns zero (0) if it completed execution successfully. Non-zero return values signify an error.
POSIX requires that an implementation of atexit
allow at least ATEXIT_MAX (32) such functions to be registered.
ISO/IEC 9899:1999 specification (PDF). p. 315, § 7.20.4.2.
atof
[edit | edit source]Prototype
[edit | edit source]double atof (const char *str);
Description
[edit | edit source]This converts a string into a floating point numerical representation. atof
stands for ASCII to float. It is included in the C standard library header file stdlib.h
. Its prototype is as follows:
The str
argument points to a string, represented by an array of characters, containing the character representation of a floating point value. If the string is not a valid textual representation of a double
, atof
will silently fail, returning zero (0.0) in that case. [1]
Note that while atoi
and atol
return variable types corresponding with their name ("atoi
" returns an integer and "atol
" returns a long integer), atof however, does not return a float
, it returns a double
.
A related function is sscanf. This function extracts values from strings and its return argument is the number of valid values it managed to extract (so, unlike atof
, sscanf
can be used to test if a string starts with a valid number).
atoi
[edit | edit source]Prototype
[edit | edit source]int atoi(const char *str);
Description
[edit | edit source]This function converts a string into an integer numerical representation. atoi
stands for ASCII to integer. It is included in the C standard library header file stdlib.h
. Its prototype is as follows:
The str
argument is a string, represented by an array of characters, containing the characters of a signed integer number. The string must be null-terminated. When atoi encounters a string with no numerical sequence, it returns zero (0).
There are several variants of the atoi function, atol, atof and atoll , which are used to convert a string into a long
, double
, or long
long
type, respectively. The atoll was formerly known as atoq and was included into C99.
It is impossible to tell whether the string holds valid sequence of digits that represents the number 0 or invalid number as the function returns 0 in both cases. The newer function strtol does not have this deficiency.
atoi is neither thread-safe, nor async-cancel safe on some operating systems.[2]
Also, atoi only converts base ten ascii values (this may also be a benefit depending on perspective). strtol and other functions support alternate bases such as hexadecimal and octal.
However, because of the ambiguity in returning 0 and lack of thread-safety and async-cancel safety on some operating systems, atoi is considered to be deprecated by strtol.[2]
External links
[edit | edit source]The Version 7 Unix Manual Pages © 1979 by Bell Telephone Laboratories, Incorporated.
The Version 1 Unix Manual page for atoi written by Ken Thompson (November 1971).
bsearch
[edit | edit source]Prototype
[edit | edit source]void *bsearch(const void *key, const void *base, size_t nmemb, size_t size,
int (*compare)(const void *, const void *));
Description
[edit | edit source]This function is used to search for an object in a sorted array using the binary search algorithm.[3]
bsearch is a generic function that can search in sorted arrays of any size, containing any kind of object, or pointer to object, and using any kind of comparison predicate. The genericity, however, comes at the expense of type-safety, since bsearch operates on void pointers; and is also expensive in the number of function calls (since each comparison requires a call to the comparison predicate), which have a large overhead.
The bsearch() function returns a pointer to a matching member of the array, or NULL if no match is found. If the array has multiple matching elements the return value will be a pointer to one of those elements. Which particular element is unspecified.[4]
div
[edit | edit source]div is a function in C programming language that takes two integers as parameters and returns the result of a division between them. It is specified in ANSI-C, and is included from the stdlib.h header when used. [5]
div always rounds towards 0, unlike ordinary integer division in C, where rounding for negative numbers is implementation-dependent.
div
has a prototype as follows:
div_t div (int numerator, int denominator)
The return value, div_t
is a special datatype which is specifically used in storing the results of this function. It is defined as follows:
typedef struct {
int quot;
int rem;
} div_t;
Where quot
stores the quotient and rem
stores the remainder.
ldiv and lldiv are similar functions that divide integers of type long
and long long
, respectively; and return a structure of type ldiv_t
and lldiv_t
, respectively.
ldiv_t ldiv (long numerator, long denominator );
lldiv_t lldiv (long long numerator, long long denominator);
See also
[edit | edit source]- stdlib.h
- stdio.h
exit
[edit | edit source]On many computer operating systems, a computer process terminates its execution by making an exit system call. More generally, an exit in a multithreading environment means that a thread of execution has stopped running. The operating system reclaims resources (memory, files, etc.) that were used by the process. The process is said to be a dead process after it terminates.
How it works
[edit | edit source]Under Unix and Unix-like operating systems, a process is started when its parent process executes a fork system call. The parent process may then wait for the child process to terminate, or may continue execution (possibly forking off other child processes). When the child process terminates ("dies"), either normally by calling exit, or abnormally due to a fatal error or signal (e.g., SIGTERM, SIGINT, SIGKILL), an exit status is returned to the operating system and a SIGCHLD signal is sent to the parent process. The exit status can then be retrieved by the parent process via the wait system call.
Most operating systems allow the terminating process to provide a specific exit status to the system, which is made available to the parent process. Typically this is a small integer value, although some operating systems (e.g.,Plan 9) allow a character string to be specified.
Clean up
[edit | edit source]The exit operation typically performs clean-up operations within the process space before returning control back to the operating system. Some systems and programming languages allow user subroutines to be registered so that they are invoked at program termination before the process actually terminates for good. As the final step of termination, a primitive system exit call is invoked, informing the operating system that the process has terminated and allows it to reclaim the resources used by the process.
It is sometimes possible to bypass the usual cleanup; C99 offers the _exit()
function which terminates the current process without any extra program clean-up. This may be used, for example, in a fork-exec routine when the exec
call fails to replace the child process; calling atexit
routines would erroneously release resources belonging to the parent.
Orphans and zombies
[edit | edit source]Some operating systems handle a child process whose parent process has terminated in a special manner. Such an orphan process becomes a child of a special root process, which then waits for the child process to terminate. Likewise, a similar strategy is used to deal with a zombie process, which is a child process that has terminated but whose exit status is ignored by its parent process. Such a process becomes the child of a special parent process, which retrieves the child's exit status and allows the operating system to complete the termination of the dead process. Dealing with these special cases keeps the system process table in a consistent state.
External links
[edit | edit source]malloc
[edit | edit source]In computing, malloc
is a subroutine for performing dynamic memory allocation. malloc
is part of the standard library and is declared in the stdlib.h
header.
Many implementations of malloc
are available, each of which performs differently depending on the computing hardware and how a program is written. Performance varies in both execution time and required memory. The pointer to memory allocated using malloc must eventually be passed to the free
subroutine to deallocate the memory in order to avoid memory leaks.
Dynamic memory allocation in C
[edit | edit source]The malloc
function is one of the functions in standard C to allocate memory. Its function prototype is
void *malloc(size_t size);
which allocates size
bytes of memory. If the allocation succeeds, a pointer to the block of memory is returned. This pointer is guaranteed to be suitably aligned to any type (including struct and such), otherwise a NULL pointer is returned.
Memory allocated via malloc
is persistent: it will continue to exist, even after the program leaves the scope which called the allocation, until the program terminates or the memory is explicitly deallocated by the programmer. This is achieved by use of the free
subroutine. Its prototype is
void free(void *pointer);
which releases the block of memory pointed to by pointer
. pointer
must have been previously returned by malloc
, calloc
, or realloc
and pointer
must not be used after it has been passed to free. In particular memory allocated via new or new[] should not be passed to free, and pointers which did not come from a malloc (e.g. stack variables) or which have already been freed must not be sent to free. It is safe to call free on a NULL pointer, which has no effect.
Usage example
[edit | edit source]The standard method of creating an array of 10 int objects:
int array[10];
However, if one wishes to allocate a similar array dynamically, the following code could be used:
/* Allocate space for an array with ten elements of type
int. */
int *ptr = (int *) malloc(10 * sizeof (int));
if (ptr == NULL) {
/* Memory could not be allocated, the program should
handle the error here as appropriate. */
} else {
/* Allocation succeeded. Do something. */
free(ptr); /* We are done with the int objects, and
free the associated pointer. */
ptr = NULL; /* The pointed-to-data must not be used again,
unless re-assigned by using malloc
again. */
}
malloc
returns a null pointer to indicate that no memory is available, or that some other error occurred which prevented memory being allocated.
Since there is a possibility that a call to malloc
may fail for lack of sufficient memory, it is often convenient to define a macro that invokes malloc
and exits when malloc
fails. A possible macro definition is:
if(!(ptr=malloc(sizeof(int))))
{
fprintf(stderr,"Insufficient memory"); /* Prints the necessary error statement. */
exit(EXIT_FAILURE); /* Exits <code>malloc</code> as there is insufficient memory. */
}
The macro given for this would be :
#define MALLOC(p,s) /*Here p & s are 2 integer pointer & variable respectively. */ \
if(!((p)=malloc(s))) \
{ \
fprintf(stderr,"Insufficient memory"); /* Prints the necessary error statement. */ \
exit(EXIT_FAILURE); /* Exits <code>malloc</code> as there is insufficient memory. */ \
}
So the above basic code can be replaced with just one line as:
MALLOC(ptr,sizeof(int));
A useful idiom with malloc
is shown in this example:
int *ptr = malloc(10 * sizeof(*ptr));
That is, instead of writing a hard-wired type into the argument to malloc, one
uses the sizeof
operator on the content of the pointer to be allocated.
This ensures that the types on the left and right of the assignment will never get
out of sync when code is revised.
'C' function for creating & returning a two dimensional array of size of m*n
int **create(int m, n)
{
int **p, i;
p = (int **)malloc(m*sizeof(int*));/* this will store base order of all the row in p */
for(i = 0; i < m; i++)
p[i] = (int *)malloc(n*sizeof(int));/* this will create m row of n elements */
return p;
}
Casting and type safety
[edit | edit source]malloc
returns a void pointer (void *
), which indicates that it is a pointer to a region of unknown data type. The lack of a specific pointer type returned from malloc
is type-unsafe behaviour: malloc
allocates based on byte count but not on type.
One may "cast" (see type conversion) this pointer to a specific type:
int *ptr;
ptr = malloc(10 * sizeof (*ptr)); // Without a cast
ptr = (int*)malloc(10 * sizeof (int)); // With a cast
There are advantages and disadvantages to performing such a cast.
Advantages to casting
[edit | edit source]- If the cast is present and the type of the left-hand-side pointer is subsequently changed, a warning will be generated to help the programmer in correcting behaviour that otherwise could become erroneous.
- The cast allows for older versions of
malloc
that originally returned achar *
.[6]
Disadvantages to casting
[edit | edit source]- Under the ANSI C standard, the cast is redundant.
- Adding the cast may mask failure to include the header
stdlib.h
, in which the prototype formalloc
is found.[6][7] In the absence of a prototype formalloc
, the standard requires that the C compiler assumemalloc
returns anint
. If there is no cast, a warning is issued when this integer is assigned to the pointer; however, with the cast, this warning is not produced, hiding a bug. On certain architectures and data models (such as LP64 on 64-bit systems, wherelong
and pointers are 64-bit andint
is 32-bit), this error can actually result in undefined behaviour, as the implicitly declaredmalloc
returns a 32-bit value whereas the actually defined function returns a 64-bit value. Depending on calling conventions and memory layout, this may result in stack smashing. This issue is not present in modern compilers, as they uniformly produce warnings that an undeclared function has been used, so a warning will still appear. For example, gcc's default behaviour is to show a warning that reads "incompatible implicit declaration of built-in function" regardless of whether the cast is present or not.
Related functions
[edit | edit source]calloc
[edit | edit source]malloc
returns a block of memory that is allocated for the programmer to use, but is uninitialized. The memory is usually initialized by hand if necessary—either via the memset
function, or by one or more assignment statements that dereference the pointer. An alternative is to use the calloc
function, which allocates contiguous memory and then initializes it to zero. Its prototype is
void *calloc(size_t nelements, size_t elementSize);
realloc
[edit | edit source]It is often useful to be able to shrink or enlarge a block of memory. This can be done using realloc
which returns a pointer to a memory region of the specified size, which contains the same data as the old region pointed to by pointer
(truncated to the minimum of the old and new sizes). If realloc
is able to resize the memory region in place, it allocates new storage, copies the required data, and frees the old pointer. If this allocation fails, realloc
maintains the original pointer unaltered, and returns the null pointer value. In case of expansion, the new region of memory outside the old data that is copied is uninitialized (contents are not predictable). The function prototype is
void *realloc(void *pointer, size_t size);
Common errors
[edit | edit source]The improper use of malloc
and related functions can frequently be a source of bugs.
Allocation failure
[edit | edit source]malloc
is not guaranteed to succeed—if there is no memory available, or if the program has exceeded the amount of memory it is allowed to reference, malloc
will return a null pointer, which should always be checked for after allocation. Many badly coded programs do not check for malloc
failure. Such a program would attempt to use the null pointer returned by malloc
as if it pointed to allocated memory. Most likely the program will crash; in some environments, particularly older or smaller platforms that perform no virtual memory management, zero is a valid address so the problem will not be caught.
Memory leaks
[edit | edit source]When a call to malloc
, calloc
or realloc
succeeds, the returned pointer to the allocated memory should eventually be passed to the free
function. This releases the allocated memory, allowing it to be reused to satisfy other memory allocation requests. If this is not done, the allocated memory will not be released until the process exits (and in some environments, not even then)—in other words, a memory leak will occur. Typically, memory leaks are caused by losing track of pointers, for example not using a temporary pointer for the return value of realloc
, which may lead to the original pointer being overwritten with a null pointer.
Use after free
[edit | edit source]After a pointer has been passed to free
, it becomes a dangling pointer: it references a region of memory with undefined content, which may not be available for use. The pointer's value cannot be accessed. For example:
int *ptr = malloc(sizeof (int));
free(ptr);
*ptr = 7; /* Undefined behavior */
Code like this has undefined behavior: its effect may vary. Actually even trying to read the value of a freed pointer can result in undefined behaviour (here).
Freeing unallocated memory
[edit | edit source]Another problem is when free
is passed an address that was not allocated by malloc
, realloc
or calloc
. This can be caused when a pointer to a literal string or the name of a declared array is passed to free
, for example:
char *msg = "Default message";
int tbl[100];
Passing either of the above pointers to free
will result in undefined behaviour.
Allocation size limits
[edit | edit source]The largest possible memory block malloc
can allocate depends on the host system, particularly the size of physical memory and the operating system implementation. Theoretically, the largest number should be the maximum value that can be held in a size_t
type, which is an implementation-dependent unsigned integer representing the size of an area of memory. The maximum value is 2CHAR_BIT*sizeof(size_t) − 1
, or the constant SIZE_MAX
in the C99 standard.
External links
[edit | edit source]- Definition of malloc in IEEE Std 1003.1 standard
- The design of the basis of the glibc allocator, by Doug Lea
- The ptmalloc homepage, by Wolfram Gloger
- The Hoard homepage, by Emery Berger
- The nedmalloc homepage, by Niall Douglas
- The jemalloc homepage, by Jason Evans
- TCMalloc homepage, a high-performance malloc developed by Google
- Simple Memory Allocation Algorithms on OSDEV Community
- Hoard: A Scalable Memory Allocator for Multithreaded Applications by Emery Berger
- Scalable Lock-Free Dynamic Memory Allocation by Maged M. Michael
- Inside memory management - The choices, tradeoffs, and implementations of dynamic allocation by Jonathan Bartlett
- Memory Reduction (GNOME) wiki page with lots of information about fixing malloc
- C99 standard draft, including TC1/TC2/TC3
- Some useful references about C
- ISO/IEC 9899 – Programming languages – C
qsort
[edit | edit source]qsort is a function used to sort elements in an array. It is named after the quicksort algorithm, although the C standard does not require it to be implemented using any specific algorithm.[8]
qsort
is a generic function that can sort arrays of any size, containing any kind of object (although, if the objects are not the same in size, pointers have to be used) and using any kind of comparison predicate. The genericity, however, comes at the expense of type-safety, since qsort
operates on void pointers.
Prototype
[edit | edit source]void qsort(void *base, size_t nmemb, size_t size, int (*compare)(const void *, const void *));
Behaviour
[edit | edit source]The contents of the array are sorted in order according to a comparison function pointed to by compare. When items compare equal, their order in resulting array is unspecified, meaning qsort is not required to be a stable sort.
strtod
[edit | edit source]strtod (string to double) converts a character string to a double precision floating-point value[9]. It is defined as:
double strtod ( const char * str, char ** endptr );
Overview
[edit | edit source]The strtod function parses the C string str interpreting its content as a floating point number and returns its value as a double. If endptr is not a null pointer, the function also sets the value pointed by endptr to point to the first character after the number.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes as many characters as possible that are valid following a syntax resembling that of floating point literals, and interprets them as a numerical value. A pointer to the rest of the string after the last valid character is stored in the object pointed by endptr.
A valid floating point number for strtod is formed by a succession of:
- An optional plus or minus sign
- A sequence of digits, optionally containing a decimal-point character
- An optional exponent part, which itself consists on an 'e' or 'E' character followed by an optional sign and a sequence of digits.
If the first sequence of non-whitespace characters in str does not form a valid floating-point number as just defined, or if no such sequence exists because either str is empty or contains only whitespace characters, no conversion is performed.
Parameters
[edit | edit source]str
- C string beginning with the representation of a floating-point number.
endptr
- Reference to an already allocated object of type char*, whose value is set by the function to the next character in str after the numerical value. This parameter can also be a null pointer, in which case it is not used.
Return value
[edit | edit source]On success, the function returns the converted floating point number as a double value. If no valid conversion could be performed, a zero value (0.0) is returned. If the correct value is out of the range of representable values, a positive or negative HUGE_VAL is returned, and the global variable errno is set to ERANGE. If the correct value would cause underflow, zero is returned and errno is set to ERANGE.
The strtod function is included in stdlib.h
.
strtol
[edit | edit source]strtol is a function in the C programming language that converts a string into a long integer. strtol
stands for string to long. It is included in the C standard library header file stdlib.h
. Its prototype is as follows:
long strtol(const char *restrict str, char **restrict end, int base);
The str
argument points to a string, represented by an array of characters, containing the character representation of a signed integer value. The string must be null-terminated. The base
argument specifies the number base to use, from 2 to 36. If the number base is greater than 10, alphabetic characters ('A'
up to 'Z'
) are used as digits in the representation. After the conversion, the value pointed to by end
is set to point to the character following the last valid numeric character in the string and the converted integer value is returned. If the string does not contain a valid numerical sequence, zero (0) is returned and the global variable errno
is set to EINVAL
.
There also exist similar variants of these function named strtoul
, strtoll
and strtoull
which parses and returns an integer of the type unsigned long
, long long
, and unsigned long long
respectively.
Standards conformance
[edit | edit source]The strtol function is part of the ISO standard C library (C89, 1989), and the strtoll function was added as part of the C99 library (1999). It was added to the standard C library as a more well-behaved replacement for the existing atoi function.
References
[edit | edit source]- strtol at OpenGroup.org
- Using strtol correctly and portably
system
[edit | edit source]In the C standard library, system is a function used to execute subprocesses and commands. It is defined in stdlib.h
header. It differs from the exec
/spawn
family of functions in that instead of passing arguments to an executed object, a single string is passed to the system shell, typically the POSIX shell, /bin/sh -c
.
Prototype
[edit | edit source]int system (const char *command);
Behavior
[edit | edit source]The system
function is blocking; that is, the call will wait until the child process terminates and return its exit value. During this time, SIGCHLD
will be blocked as system
waits for the child to die; also, SIGINT
and SIGQUIT
are ignored, so to ensure responsiveness the programmer should check the return value to see if the user is trying to terminate the process. On error, system will return -1 on failure prior to or at fork
(e.g. process count limit reached) but will return 127 on failure after fork
(e.g. unable to execute sh); this is indistinguishable from the command exiting with status 127.
Under POSIX, system
forks and execs /bin/sh
with two arguments: "-c
" and command
. While the behavior of sh is specified elsewhere, it is instructive to consider that command
need not be a single command; it can in fact be a pipeline or even a series of pipelines. For example, consider a program that wishes to display a screenshot:
system ("pngtopnm \"My Screenshot.png\" | pnmtoxwd > out.xwd && xwud out.xwd");
This line exhibits an important consideration: since command
will be parsed as a shell command line, quotes around e.g. file names must be escaped. This however raises security considerations, since if command
is constructed from user-supplied data, an attacker may be able to break out of any quoting and execute an arbitrary command in the context of the parent; indeed, this is almost the canonical code injection exploit. It is thus considered sensible to only employ system
on predetermined command strings, using other functions (spawn
et al.) to pass user-supplied data in argv or passing such data through pipes or temporary files.
The child spawned by system
inherits its parent's standard streams; thus the child can receive keyboard input and write to the terminal. Note that this means that the parent will not receive the child's output, except through the use of a redirection or tee.
External links
[edit | edit source]References
[edit | edit source]- ↑ ISO/IEC 9899:1999 specification, p. 307, § 7.20.1.1
- ↑ a b http://www.codecogs.com/reference/c/stdlib.h/atoi.php
- ↑ ISO/IEC 9899:1999 specification (PDF). p. 318, § 7.20.5.1.
- ↑ UNIX man pages:
man 3 bsearch
- ↑ http://www.open-std.org/JTC1/SC22/wg14/www/docs/n1124.pdf chapter 7.20.6.2
- ↑ a b FAQ > Explanations of... > Casting malloc on Cprogramming.com accessed at March 9, 2007
- ↑ comp.lang.c FAQ list · Question 7.7b on C-FAQ accessed at March 9, 2007
- ↑ ISO/IEC 9899:1999 specification (PDF). p. 319, § 7.20.5.2.
- ↑ ISO/IEC 9899:1999 specification (PDF). p. 308, § 7.20.1.3.