stdlib.h — Man Page
This manual page is part of the POSIX Programmer’s Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux.
Synopsis
Description
Some of the functionality described on this reference page extends the ISO C standard. Applications shall define the appropriate feature test macro (see the System Interfaces volume of POSIX.1-2017, Section 2.2, The Compilation Environment) to enable the visibility of these symbols in this header.
The <stdlib.h> header shall define the following macros which shall expand to integer constant expressions:
Unsuccessful termination for exit(); evaluates to a non-zero value.
Successful termination for exit(); evaluates to 0.
Maximum value returned by rand(); at least 32767.
The <stdlib.h> header shall define the following macro which shall expand to a positive integer expression with type size_t:
Maximum number of bytes in a character specified by the current locale (category LC_CTYPE).
In the POSIX locale the value of
The <stdlib.h> header shall define NULL as described in <stddef.h>.
The <stdlib.h> header shall define the following data types through typedef:
Structure type returned by the div() function.
Structure type returned by the ldiv() function.
Structure type returned by the lldiv() function.
As described in <stddef.h>.
As described in <stddef.h>.
In addition, the <stdlib.h> header shall define the following symbolic constants and macros as described in <sys/wait.h>:
The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.
C Library — <stdlib.h>
The stdlib.h header defines four variable types, several macros, and various functions for performing general functions.
Library Variables
Following are the variable types defined in the header stdlib.h −
This is the unsigned integral type and is the result of the sizeof keyword.
This is an integer type of the size of a wide character constant.
This is the structure returned by the div function.
This is the structure returned by the ldiv function.
Library Macros
Following are the macros defined in the header stdlib.h −
EXIT_FAILURE
This is the value for the exit function to return in case of failure.
EXIT_SUCCESS
This is the value for the exit function to return in case of success.
This macro is the maximum value returned by the rand function.
This macro is the maximum number of bytes in a multi-byte character set which cannot be larger than MB_LEN_MAX.
Library Functions
Following are the functions defined in the header stlib.h −
Converts the string pointed to, by the argument str to a floating-point number (type double).
Converts the string pointed to, by the argument str to an integer (type int).
Converts the string pointed to, by the argument str to a long integer (type long int).
Converts the string pointed to, by the argument str to a floating-point number (type double).
Converts the string pointed to, by the argument str to a long integer (type long int).
Converts the string pointed to, by the argument str to an unsigned long integer (type unsigned long int).
Allocates the requested memory and returns a pointer to it.
Deallocates the memory previously allocated by a call to calloc, malloc, or realloc.
Allocates the requested memory and returns a pointer to it.
Attempts to resize the memory block pointed to by ptr that was previously allocated with a call to malloc or calloc.
Causes an abnormal program termination.
Causes the specified function func to be called when the program terminates normally.
Causes the program to terminate normally.
Searches for the environment string pointed to by name and returns the associated value to the string.
The command specified by string is passed to the host environment to be executed by the command processor.
Performs a binary search.
Returns the absolute value of x.
Divides numer (numerator) by denom (denominator).
Returns the absolute value of x.
Divides numer (numerator) by denom (denominator).
Returns a pseudo-random number in the range of 0 to RAND_MAX.
This function seeds the random number generator used by the function rand.
Returns the length of a multibyte character pointed to by the argument str.
Converts the string of multibyte characters pointed to by the argument str to the array pointed to by pwcs.
Examines the multibyte character pointed to by the argument str.
Converts the codes stored in the array pwcs to multibyte characters and stores them in the string str.
C Programming/stdlib.h
stdlib.h is the header of the general purpose standard library of C programming language which includes functions involving memory allocation, process control, conversions and others. It is compatible with C++ and is known as cstdlib in C++. The name «stdlib» stands for «standard library».
Contents
Member functions [ edit | edit source ]
Members of the stdlib.h can be classified into the following categories: conversion, memory, process control, sort and search, mathematics.
| Name | Description |
|---|---|
| Type Conversion | |
| atof | string to double (NOT float) |
| atoi | string to integer |
| atol | string to long |
| strtod | string to double |
| strtol | string to long int |
| strtoul | string to unsigned long int |
| strtoll | string to long long int |
| strtoull | string to unsigned long long int |
| Pseudo-random sequence generation | |
| int rand(void) | generates a pseudo-random number |
| int random(void) | generates a pseudo-random number (not standard C; provided by POSIX) |
| void srand(unsigned int seed) | set the rand() pseudo-random generator seed [common convention uses time() to seed] |
| void srandom(unsigned int seed) | set the random() pseudo-random generator seed [common convention uses time() to seed] (not standard C; provided by POSIX) |
| Memory allocation and deallocation | |
| malloc calloc realloc |
allocate memory from the heap |
| free | release memory back to the heap |
| Process control | |
| /abort/ | terminate execution abnormally |
| atexit | register a callback function for program exit |
| exit | terminate program execution |
| getenv | retrieve an environment variable |
| system | execute an external command |
| Sorting, searching and comparison | |
| bsearch | binary search an array |
| qsort | sort an array |
| Mathematics | |
| int abs(int) | absolute value of an integer. |
| long int labs(long int) | absolute value of a long integer. |
| div | integer division (returns quotient and remainder) |
| ldiv | long integer division (returns quotient and remainder) |
| Multibyte / Wide Characters | |
| mblen | size of multibyte char [1] |
| mbtowc, wctomb, mbstowcs, wcstombs | multibyte & wide character conversion [2] |
Member constants [ edit | edit source ]
NULL [ edit | edit source ]
The stdlib.h and stddef.h header files define the macro NULL , which yields a null pointer constant, and represents a pointer value that is guaranteed not to point to a valid address in memory.
Variants [ edit | edit source ]
NULL may be defined as a constant expression equal to int zero, long int zero, or zero cast to a void * pointer:
Although the null pointer constant is always represented in C by the symbolic constant 0 or by 0 cast to a void pointer, the actual bit representation of such a pointer is system-specific and may contain one-bits.
Member data types [ edit | edit source ]
size_t [ edit | edit source ]
The size_t definition shall be provided to a referencing piece of code by including this header file. In fact most implementations don’t have it defined literally in this file but instead include the file stddef.h as, for example, the standard library of the GNU C compiler does. The direct inclusion of stddef.h for application code is totally valid and thus can replace stdlib.h in cases where no other members from this file are needed or desired. This whole header file design conforms with e.g. the C99 ISO/ANSI standard definition. [3]
div_t, ldiv_t [ edit | edit source ]
Two less widely used datatypes, div_t and ldiv_t , are also defined. They are the return types of the div and ldiv functions. The standard defines them as:
Stdlib.h
stdlib.h — заголовок (заголовочный файл) стандартной библиотеки общего назначения языка Си, который содержит в себе функции, занимающиеся выделением памяти, контроль процесса выполнения программы, преобразования типов и другие. Заголовок вполне совместим с C++ и в C++ известен как cstdlib . Название «stdlib» расшифровывается как «standard library» (стандартная библиотека).
Содержание
Member functions
Члены stdlib.h можно разделить на следующие категории: преобразования типов, управление памятью, контроль процесса, сортировка и поиск, математика.
| Имя | Описание |
|---|---|
| Преобразование типов | |
| atof | строка в число двойной точности (НЕ float) |
| atoi | строка в целое число |
| atol | строка в длинное целое число |
| strtod | строка в число двойной точности (double) |
| strtol | строка в длинное целое число |
| strtoul | строка в беззнаковое длинное целое число (unsigned long int) |
| Генерация псевдослучайных последовательностей | |
| rand | генерирует псевдослучайное значение |
| srand | устанавливает начальное значение генератора псевдослучайных чисел |
| Выделение и освобождение памяти | |
| malloc calloc realloc |
выделяет память из кучи |
| free | освобождает память обратно в кучу |
| Контроль процесса выполнения программы | |
| abort | некорректное завершение выполнения |
| atexit | регистрирует обратный вызов функции для выхода из программы |
| exit | завершает выполнение программы |
| getenv | извлекает переменные окружения |
| system | выполняет внешнюю команду |
| Сортировка и поиск | |
| bsearch | двоичный поиск в массиве |
| qsort | сортировка массива |
| Математика | |
| abs labs |
абсолютная величина |
| div ldiv |
деление целых чисел |
| Многобайтовые операции/ широкие символы | |
| mblen | размер многобайтовых символов [1] |
| mbtowc, wctomb, mbstowcs, wcstombs | преобразование многобайтовых и широких символов [2] |
Члены-константы
Заголовочные файлы stdlib.h и stddef.h определяют макрос NULL, который порождает константный нуль-указатель, и представляет собой значение указателя, гарантирующего корректность указателя, не указывающего на действительный (корректный) адрес в памяти.
Варианты
NULL может быть определен как константное выражение, равное целому нулевому числу (нулю), длинному целому нулю, или нуль приводится к указателю типа void *:
Несмотря на то, что константа нуль-указателя всегда представляется в Си символьной константой 0 или 0, приведенным к void-указателю, реальное битовое представление подобного указателя зависит от системы и может содержать однобитовые значения.
Типы членов-данных
size_t
Заголовочные файлы stdlib.h и stddef.h определяют тип данных, называемый size_t [3] , который используется для представления размера объекта. Библиотечные функции, использующие размеры, ожидают типа size_t , а оператор sizeof превращается в size_t .
Настоящий тип size_t платформо-независим; распространенной ошибкой является подразумевание size_t как беззнаковое целое ( unsigned int ), что может привести к ошибкам программирования, [4] причем в первую очередь это касается 64-битных архитектур.
div_t, ldiv_t
Также определены два менее широко используемых типа данных div_t и ldiv_t . Они являются возвращаемыми типами функций div и ldiv. Стандарт определяет их следующим образом:
Нестандартные функции
itoa — общая функция, входящая во множество реализаций stdlib.h, но стандарт не определяет функцию. Возможно, ее так часто включают в библиотеки благодаря ее описанию в книге Язык программирования Си. Аналогичного эффекта можно добиться при помощи функции sprintf, которая определена в стандарте.
См. также
Примечания
- ↑C++ Resources Network — stdlib.h проверено 2009 12 15
- ↑C++ Resources Network — stdlib.h проверено 2009 12 15
- ↑ Согласно стандарту ISO/IEC 9899 C99, Глава 7.20 General utilities <stdlib.h> (point number 2) и Приложение B.19 General utilities <stdlib.h>. Определение может также содержаться в stddef.h, если кто-то захочет избежать подключения всей stdlib.
- ↑20 issues of porting C++ code on the 64-bit platform
Ссылки
-
(англ.) (англ.) (рус.) (рус.)
Wikimedia Foundation . 2010 .
Полезное
Смотреть что такое «Stdlib.h» в других словарях:
Stdlib.h — is the header of the general purpose standard library of C programming language which includes functions involving memory allocation, process control, conversions and others. It is compatible with C++ and is known as cstdlib in C++. The name… … Wikipedia
Stdlib.h — Saltar a navegación, búsqueda stdlib.h (std lib: standar library o biblioteca estándar) es el archivo de cabecera de la biblioteca estándar de propósito general del lenguaje de programación C. Contiene los prototipos de funciones de C para… … Wikipedia Español
stdlib.h — (std lib: standard library o biblioteca estándar) es el archivo de cabecera de la biblioteca estándar de propósito general del lenguaje de programación C. Contiene los prototipos de funciones de C para gestión de memoria dinámica, control de… … Wikipedia Español
stdlib.h — Стандартная библиотека языка программирования С assert.h complex.h ctype.h errno.h fenv.h float.h inttypes.h iso646.h limits.h locale.h math.h setjmp.h signal.h stdarg.h stdbool.h stddef.h stdint.h … Википедия
System (stdlib) — Saltar a navegación, búsqueda La función system() está incluída en la biblioteca cuya cabecera es <stdlib.h>. System permite ejecutar a su vez otras funciones como: cls , dir o pause . Por ejemplo, al escribir system ( pause ) se está… … Wikipedia Español
system (stdlib) — system() es una función del lenguaje de programación C incluida en su biblioteca estándar, dentro de la cabecera <stdlib.h>. Sirve para ejecutar subprocesos o comandos del sistema operativo. «system» permite ejecutar a su vez otras… … Wikipedia Español
Dao (programming language) — Infobox programming language name = Dao paradigm = Multi paradigm year = 2006 designer = Limin Fu latest release version = dao 1.0 preview latest release date = 2008 04 25 typing = statically typed or dynamically typed influenced by = C++, Lua,… … Wikipedia
Strtod — is a C language function that converts an ASCII string to a double precision value. It is utilized via the following sequence:double strtod(const char *restrict, char **restrict); [OpenGroup Technical Standards Documentation] Strtod is included… … Wikipedia
strtod — (сокр. от string to double, «строку в число двойной точности») функция языка Си, конвертирующая символ строки в число с плавающей запятой двойной точности. Определение функции имеет вид: double strtod ( const char * str, char ** endptr… … Википедия
Memory leak — A memory leak, in computer science (or leakage, in this context), occurs when a computer program consumes memory but is unable to release it back to the operating system. In object oriented programming, a memory leak happens when an object is… … Wikipedia
