C Programming/stdlib.h/Function reference

Description
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.

Description
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.

Description
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  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  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  allow at least ATEXIT_MAX (32) such functions to be registered.

Description
This converts a string into a floating point numerical representation. stands for ASCII to float. It is included in the C standard library header file. Its prototype is as follows:

The  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,   will silently fail, returning zero (0.0) in that case.

Note that while  and   return variable types corresponding with their name (" " returns an integer and " " returns a long integer), atof however, does not return a  , it returns a.

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,    can be used to test if a string starts with a valid number).

Description
This function converts a string into an integer numerical representation. stands for ASCII to integer. It is included in the C standard library header file. Its prototype is as follows:

The  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 ,  , or     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.

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.

Description
This function is used to search for an object in a sorted array using the binary search algorithm.

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.

div
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.

div always rounds towards 0, unlike ordinary integer division in C, where rounding for negative numbers is implementation-dependent.

has a prototype as follows:

The return value,  is a special datatype which is specifically used in storing the results of this function. It is defined as follows: Where  stores the quotient and   stores the remainder.

ldiv and lldiv are similar functions that divide integers of type  and , respectively; and return a structure of type   and  , respectively.

exit
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
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
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  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  call fails to replace the child process; calling   routines would erroneously release resources belonging to the parent.

Orphans and zombies
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.

malloc
In computing,   is a subroutine for performing dynamic memory allocation. is part of the standard library and is declared in the  header.

Many implementations of  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  subroutine to deallocate the memory in order to avoid memory leaks.

Dynamic memory allocation in C
The  function is one of the functions in standard C to allocate memory. Its function prototype is which allocates  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  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  subroutine. Its prototype is which releases the block of memory pointed to by. must have been previously returned by,  , or   and   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
The standard method of creating an array of 10 int objects: However, if one wishes to allocate a similar array dynamically, the following code could be used:

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  may fail for lack of sufficient memory, it is often convenient to define a macro that invokes   and exits when   fails. A possible macro definition is: as there is insufficient memory. */ }

The macro given for this would be : as there is insufficient memory. */ \ } So the above basic code can be replaced with just one line as:

A useful idiom with  is shown in this example:

That is, instead of writing a hard-wired type into the argument to malloc, one uses the  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

Casting and type safety
returns a void pointer, which indicates that it is a pointer to a region of unknown data type. The lack of a specific pointer type returned from  is type-unsafe behaviour:   allocates based on byte count but not on type.

One may "cast" (see type conversion) this pointer to a specific type:

There are advantages and disadvantages to performing such a cast.

Advantages to casting

 * 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  that originally returned a.

Disadvantages to casting

 * Under the ANSI C standard, the cast is redundant.
 * Adding the cast may mask failure to include the header, in which the prototype for   is found. In the absence of a prototype for  , the standard requires that the C compiler assume   returns an  . 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, where   and pointers are 64-bit and   is 32-bit), this error can actually result in undefined behaviour, as the implicitly declared   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.

calloc
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&mdash;either via the   function, or by one or more assignment statements that dereference the pointer. An alternative is to use the   function, which allocates contiguous memory and then initializes it to zero. Its prototype is

realloc
It is often useful to be able to shrink or enlarge a block of memory. This can be done using  which returns a pointer to a memory region of the specified size, which contains the same data as the old region pointed to by   (truncated to the minimum of the old and new sizes). If  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,  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

Common errors
The improper use of  and related functions can frequently be a source of bugs.

Allocation failure
is not guaranteed to succeed&mdash;if there is no memory available, or if the program has exceeded the amount of memory it is allowed to reference,  will return a null pointer, which should always be checked for after allocation. Many badly coded programs do not check for  failure. Such a program would attempt to use the null pointer returned by  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
When a call to,   or   succeeds, the returned pointer to the allocated memory should eventually be passed to the   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)&mdash;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, which may lead to the original pointer being overwritten with a null pointer.

Use after free
After a pointer has been passed to, 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: 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
Another problem is when  is passed an address that was not allocated by ,   or. This can be caused when a pointer to a literal string or the name of a declared array is passed to, for example: Passing either of the above pointers to  will result in undefined behaviour.

Allocation size limits
The largest possible memory block  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  type, which is an implementation-dependent unsigned integer representing the size of an area of memory. The maximum value is, or the constant   in the C99 standard.

qsort
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.

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  operates on void pointers.

Behaviour
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
strtod (string to double) converts a character string to a double precision floating-point value. It is defined as:



Overview
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
str endptr
 * C string beginning with the representation of a floating-point number.
 * 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
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.

strtol
strtol is a function in the C programming language that converts a string into a long integer. stands for string to long. It is included in the C standard library header file. Its prototype is as follows:

The  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  argument specifies the number base to use, from 2 to 36. If the number base is greater than 10, alphabetic characters ( up to  ) are used as digits in the representation. After the conversion, the value pointed to by  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  is set to.

There also exist similar variants of these function named,   and   which parses and returns an integer of the type  ,  , and   respectively.

Standards conformance
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.

system
In the C standard library, system is a function used to execute subprocesses and commands. It is defined in  header. It differs from the /  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,.

Behavior
The  function is blocking; that is, the call will wait until the child process terminates and return its exit value. During this time,  will be blocked as   waits for the child to die; also,   and   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  (e.g. process count limit reached) but will return 127 on failure after   (e.g. unable to execute sh); this is indistinguishable from the command exiting with status 127.

Under POSIX,  forks and execs   with two arguments: " " and. While the behavior of sh is specified elsewhere, it is instructive to consider that  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:

This line exhibits an important consideration: since  will be parsed as a shell command line, quotes around e.g. file names must be escaped. This however raises security considerations, since if  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  on predetermined command strings, using other functions (  et al.) to pass user-supplied data in argv or passing such data through pipes or temporary files.

The child spawned by  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.