This wiki is being migrated to http://www.github.com/z88dk/z88dk/wiki

User Tools

Site Tools


libnew:stdlib

Table of Contents

STDLIB.H

MACROS

EXIT_FAILURE 0
EXIT_SUCCESS 1
NULL ((void*)(0)) pointer to nothing
RAND_MAX 32767 maximum random number generated by rand()
DTOA_FLAG_PLUS 0x40 double to ascii always includes leading sign
DTOA_FLAG_SPACE 0x20 double to ascii inserts space in front of positive doubles
DTOA_FLAG_HASH 0x10 double to ascii always includes decimal point and trailing zeroes are not removed
FTOA_FLAG_PLUS 0x40 float to ascii always includes leading sign
FTOA_FLAG_SPACE 0x20 float to ascii inserts space in front of positive doubles
FTOA_FLAG_HASH 0x10 float to ascii always includes decimal point and trailing zeroes are not removed

TYPES

size_t unsigned int
wchar_t unsigned char1
float_t float type suppresses compiler warnings2
double_t double type suppresses compiler warnings2
div_t struct { int rem; int quot; };
divu_t struct { unsigned int rem; unsigned int quot; };
ldiv_t struct { long quot; long rem; };
ldivu_t struct { unsigned long quot; unsigned long rem; };
lldiv_t3 struct { long long rem; long long quot; };
lldivu_t3 struct { unsigned long long rem; unsigned long long quot; };

1 Wide characters are not supported by the library and are aliased to chars.

2 The compilers only support one floating point type so float and double are aliased.

3 Nightly build, sdcc only.

NUMERIC CONVERSIONS

INTEGER

int atoi(const char *nptr)

Parses the C-string nptr, interpreting its content as a signed decimal number which is returned as an int. Leading whitespace is skipped and as many decimal digits as possible are taken to be part of the number. Trailing non-digit characters in the string are uninterpreted. If there is no valid decimal number, zero is returned. The decimal number returned saturates at +32767 or -32768.

char *itoa(int num, char *buf, int radix)

Writes the integer num as a nul-terminated string into the buffer pointed at by buf using the indicated radix. Returns a pointer in buf to the terminating NUL char. If radix is ten, indicating a decimal number, num is treated as signed so that a negative number will have a preceding minus sign written to the buffer. Any other radix treats num as an unsigned number.

The buffer pointed to by buf must be large enough to hold the result to avoid buffer overrun (minimum 17 bytes for base 2). If buf is 0 the function immediately returns with 0 result and carry flag set.

If an error occurs, the carry flag is set, 0 is returned and errno will be set to:

  • [EINVAL] radix is not in the range [2,36]

char *utoa(uint16_t num, char *buf, int radix)

As itoa() but num is treated as unsigned. This only differs from itoa() for base 10 conversion.

int _strtoi_(char *nptr, char **endptr, int base)

As strtol() but with 16-bit result. Out of range numbers saturate at +32767 or -32768.

uint16_t _strtou_(char *nptr, char **endptr, int base)

As strtoul() but with 16-bit result. Out of range numbers saturate at +65535. Negative numbers receive two's complement.

LONG

long atol(const char *nptr)

Parses the C-string nptr, interpreting its content as a signed decimal number which is returned as a long. Leading whitespace is skipped and as many decimal digits as possible are taken to be part of the number. Trailing non-digit characters in the string are uninterpreted. If there is no valid decimal number, zero is returned. The decimal number returned saturates at +231-1 or -231.

char *ltoa(long num, char *buf, int radix)

Writes the long num as a nul-terminated string into the buffer pointed at by buf using the indicated radix. Returns a pointer in buf to the terminating NUL char. If radix is ten, indicating a decimal number, num is treated as signed so that a negative number will have a preceding minus sign written to the buffer. Any other radix treats num as an unsigned number.

The buffer pointed to by buf must be large enough to hold the result to avoid buffer overrun (minimum 33 bytes for base 2). If buf is 0 the function immediately returns with 0 result and carry flag set.

If an error occurs, the carry flag is set, 0 is returned and errno will be set to:

  • [EINVAL] radix is not in the range [2,36]

char *ultoa(uint32_t num, char *buf, int radix)

As ltoa() but num is treated as unsigned. This only differs from ltoa() for base 10 conversion.

long strtol(const char *nptr, char **endptr, int base)

Parses the C-string nptr, interpreting its content as a signed integral number of radix base and returns this number as a long. If endptr is not 0, the function also sets endptr to point to the first character after the number.

The function first discards any leading whitespace and then accepts the longest string of characters that can compose a number of radix base. This number is converted to a long and returned as a result. If an overflow occurs, the result saturates at +231-1 or -231. If there are no valid digits, 0 is returned. If base is not in [0,2-36], 0 is returned.

If base is 0, the radix used is determined from the string. A leading '0x' or '0X' indicates the number is base 16, a leading '0' indicates the number is base 8, otherwise the number is base 10.

If an error occurs, the return value is as described above, carry flag will be set and errno will be set to:

  • [EINVAL] no valid digits in the radix indicated
  • [EINVAL] radix is not in the range [0,2-36]
  • [ERANGE] an overflow occurred during conversion

unsigned long strtoul(const char *nptr, char **endptr, int base)

As strtol() but out of range numbers saturate at +232-1. Negative numbers receive two's complement.

LONG LONG

long long atoll(char *buf)

(nightly build, sdcc)

An alias for strtoll(buf, 0, 10)

char *lltoa(long long num, char *buf, int radix)

(nightly build, sdcc)

Writes the long long num as a nul-terminated string into the buffer pointed at by buf using the indicated radix. Returns a pointer in buf to the terminating NUL char. If radix is ten, indicating a decimal number, num is treated as signed so that a negative number will have a preceding minus sign written to the buffer. Any other radix treats num as an unsigned number.

The buffer pointed to by buf must be large enough to hold the result to avoid buffer overrun (minimum 65 bytes for base 2). If buf is 0 the function immediately returns with 0 result and carry flag set.

If an error occurs, the carry flag is set, 0 is returned and errno will be set to:

  • [EINVAL] radix is not in the range [2,36]

char *ulltoa(unsigned long long num, char *buf, int radix)

(nightly build, sdcc)

As lltoa() but num is treated as unsigned. This only differs from lltoa() for base 10 conversion.

long long strtoll(const char *nptr, char **endptr, int base)

(nightly build, sdcc)

Parses the C-string nptr, interpreting its content as a signed integral number of radix base and returns this number as a long long. If endptr is not 0, the function also sets endptr to point to the first character after the number.

The function first discards any leading whitespace and then accepts the longest string of characters that can compose a number of radix base. This number is converted to a long long and returned as a result. If an overflow occurs, the result saturates at +263-1 or -263. If there are no valid digits, 0 is returned. If base is not in [0,2-36], 0 is returned.

If base is 0, the radix used is determined from the string. A leading '0x' or '0X' indicates the number is base 16, a leading '0' indicates the number is base 8, otherwise the number is base 10.

If an error occurs, the return value is as described above, carry flag will be set and errno will be set to:

  • [EINVAL] no valid digits in the radix indicated
  • [EINVAL] radix is not in the range [0,2-36]
  • [ERANGE] an overflow occurred during conversion

unsigned long long strtoull(const char *nptr, char **endptr, int base)

(nightly build, sdcc)

As strtoll() but out of range numbers saturate at +264-1. Negative numbers receive two's complement.

FLOATING POINT

The compilers do not distinguish between floats and doubles so functions that purport to operate on floats are in fact aliases for the same function operating on doubles.

double atof(const char *nptr)

Parses the C-string nptr, interpreting its content as a double. Equivalent to strtod(nptr, 0).

double strtod(const char *nptr, char **endptr)

Parses the C-string nptr, interpreting its content as a double. If endptr is not 0, the function also sets endptr to point to the first character after the number.

The function first discards any leading whitespace and then accepts the longest string of characters that can compose a double. This string is converted to a double and returned as the result.

An acceptable input string encodes a double in either decimal form or hexadecimal form or contains the strings “inf”, “infinity”, “nan” or “nan(*)” in either lower case or upper case. Decimal form looks like “+-ddd.ddde+-ddd” where the signs, decimal point and exponential indicator are optional. Hexadecimal form looks like “+-0xhhh.hhhp+-ddd” where the signs, decimal point and exponential indicator are optional and the “h” indicate hexadecimal digits. Hexadecimal form represents the exact bit pattern stored in the internal double representation. Note that library configuration may disable parsing of hex strings and/or the special strings “inf”, etc.

If an error occurs, the return value is as indicated below, the carry flag is set and errno is set to:

  • [ERANGE] return +-HUGE_VAL, double is too large to be represented.
  • [EINVAL] return 0.0, invalid input
  • [EINVAL] return 0.0, nan is not supported by the float library

float strtof(const char *nptr, char **endptr)

size_t dtoa(double x, void *buf, uint16_t prec, uint16_t flags)

Writes the double x as a nul-terminated string in the form “-ddd.ddd” to the buffer pointed at by buf. prec indicates the precision and controls how many digits appear after the decimal point. If set to -1, maximum precision is indicated. flags can take on a combination of DTOA_FLAG_* logically ORed together. The DTOA_FLAG_* macros are defined at the top of this page. The return value is the number of characters written to the buffer not including the terminating NUL char.

If buf is 0, the double is not written to the buffer but the return value indicates the number of chars that would be written not including the terminating NUL. A first call with buf equal to zero can then be used to allocate a buffer that will be able to hold the result without overrun.

dtoa is similar to printf's %f converter.

size_t dtoe(double x, void *buf, uint16_t prec, uint16_t flags)

dtoe behaves the same way as dtoa except the output string is in the form “-d.ddde+dd”.

dtoe is similar to printf's %e converter.

size_t dtog(double x, void *buf, uint16_t prec, uint16_t flags)

dtog behaves the same way as dtoa except the output string is either in the form “-ddd.ddd” or “-d.ddde+dd” depending on which is most suitable. prec indicates the total number of significant digits in the result.

dtog is similar to printf's %g converter.

size_t dtoh(double x, void *buf, uint16_t prec, uint16_t flags)

dtoh behaves the same way as dtoa except the output string is in hexadecimal form “-0xh.hhhp+dd”. The hex digits represent the mantissa bits in the internal representation exactly.

dtoh is similar to printf's %a converter.

size_t ftoa(float x, void *buf, uint16_t prec, uint16_t flags)

size_t ftoe(float x, void *buf, uint16_t prec, uint16_t flags)

size_t ftog(float x, void *buf, uint16_t prec, uint16_t flags)

size_t ftoh(float x, void *buf, uint16_t prec, uint16_t flags)

PSEUDO-RANDOM SEQUENCE GENERATION

int rand(void)

Return a random number in [0,32767] and updates the seed. The random number generator is a very fast Marsaglia 32-bit XOR PRNG.

void srand(unsigned int seed)

Sets the seed for the random number generator. seed(0) is the default at startup.

uint16_t _random_uniform_cmwc_8_(void *seed)

An 8-bit Complementary-Multiply-With-Carry (CMWC) random number generator. The random number sequence generated has very high quality and is very fast. The seed is a pointer to a block of 10 bytes that is updated by the subroutine. The return value is a random number in [0,255].

uint32_t _random_uniform_xor_32_(uint32_t *seed)

This is the random number generator used by rand() and is based on a very fast 32-bit XOR RNG as described above. This entry point allows a 32-bit seed variable to be passed in that is updated by the subroutine and must be initialized to a non-zero value. The returned value is a random number in [1,2^32-1].

uint16_t _random_uniform_xor_8_(uint32_t *seed)

A very fast Marsaglia 8-bit XOR PRNG similar to the 32-bit version above. The seed is a 32-bit value that is updated by the subroutine and must have an initial non-zero value. The return value is a random number in [0,255].

MEMORY MANAGEMENT

See malloc.h.

void *aligned_alloc(size_t alignment, size_t size)

void *calloc(size_t nmemb, size_t size)

void free(void *ptr)

void *malloc(size_t size)

void *realloc(void *ptr, size_t size)

COMMUNICATION WITH THE ENVIRONMENT

void abort(void)

Abnormally terminate the program. Functions registered with atexit() or at_quick_exit() are not executed. Open files will be closed and -1 will be returned to the host on exit. Note that the implementation does not support signals so abort() cannot be intercepted by SIGABRT.

void exit(int status)

Normally terminate the program. Functions registered with atexit() are run in the reverse order they were registered. Open files are closed and status is returned to the host on exit.

void quick_exit(int status)

Normally terminate the program. Functions registered with at_quick_exit() are run in the reverse order they were registered. Open files are closed and status is returned to the host on exit.

void _Exit(int status)

Normally terminate the program. Functions registered with atexit() or at_quick_exit() are not executed. Open files will be closed and status is returned to the host on exit.

int atexit(void (*func)(void))

Registers the function func to be executed at normal program termination without arguments. Functions so registered are run when main() returns or when exit() is called by the program.

The C standard guarantees space for 32 functions to be registered but the target crts often reduce this number to lower binary size. If a program uses atexit() verify that the crt is creating enough space for all registered functions and change the default if necessary.

int at_quick_exit(void (*func)(void))

Registers the function func to be executed if at_quick_exit() is called. These functions are not called when main() returns or if exit() is called by the program.

The C standard guarantees space for 32 functions to be registered but the target crts often reduce this number to lower binary size. If a program uses at_quick_exit() verify that the crt is creating enough space for all registered functions and change the default if necessary.

int system(const char *string)

If string is 0, a non-zero return value indicates the host provides a command processor.

Otherwise string is a NUL-terminated C-string passed to the host for execution. The return value is defined by the host.

SEARCHING AND SORTING

void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *))

Search a sorted array at address base for the key. The array contains nmemb objects each of which are size bytes in length.

The comparison function compar takes as first element key and the second element is a pointer to one of the members of the base array. The function should return a negative number if the key is smaller, 0 if the key is equal, and positive non-zero number if the key is greater than the array member.

The return value is 0 if key is not found or the address of the array member if the key is found. If more than one array member is equal it is unspecified which array member is returned.

void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *))

Sorts an array of nmemb objects at address base with each object being size bytes in length.

The contents of the array is sorted in ascending order according to the comparison function compar. compar takes pointers to two objects of the array and should return negative number, 0, or non-zero positive number depending on whether the first argument is less than, equal to, or greater than the second argument.

The sorting algorithm used depends on the library configuration and is normally shellsort by default. Note that shellsort is not reentrant.

void _insertion_sort_(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *))

As qsort() but an insertion sort algorithm is used.

void _quicksort_(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *))

As qsort() but a quicksort algorithm is used.

Quicksort has several library configurations:

  • Pivot Selection. Middle item or random item. Most implementations use the faster middle item pivot selection but this method can still lead to O(n2) sorting times; it is a naive method designed to avoid long sorting times when sorting arrays that are nearly in order, which is a common case. Random pivot selection eliminates quicksort's extreme cases at the cost of more expensive pivot selection which increases average running times.
  • Enable Insertion Sort. It is faster to sort small arrays with insertion sort. With this option enabled, insertion sort is applied to small partitions.
  • Enable Equal Items Distribution. Quicksort degrades to O(n2) performance when the array contains equal items. This option tries to distribute equal items between partitions.

Library defaults typically select Middle Pivot, Insertion Sort Enabled and Equal Items Distributed.

void _shellsort_(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *))

As qsort() but a shellsort algorithm is used. Note that shellsort is not reentrant.

INTEGER ARITHMETIC

The C compilers are unable to pass structs by value so the standard C div() and ldiv() functions have been replaced by _div_() and _ldiv_() variants that communicate the structs via pointer instead.

int abs(int j)

Return the absolute value of j.

long labs(long j)

Return the absolute value of j.

long long llabs(long long j)

(nightly build, sdcc)

Return the absolute value of j.

void _div_(div_t *d, int numer, int denom)

Use a single signed division (numer / denom) to compute quotient and remainder and store that in the struct pointed at by d.

On division by zero, the quotient is +INT_MAX or -INT_MIN, the remainder is numer, carry flag is set and errno is set to:

  • [EDOM] division by zero

void _divu_(divu_t *d, unsigned int numer, unsigned int denom)

Use a single unsigned division (numer / denom) to compute quotient and remainder and store that in the struct pointed at by d.

On division by zero, the quotient is +UINT_MAX, the remainder is numer, carry flag is set and errno is set to:

  • [EDOM] division by zero

void _ldiv_(ldiv_t *d, long numer, long denom)

Use a single signed long division (numer / denom) to compute quotient and remainder and store that in the struct pointed at by d.

On division by zero, the quotient is +LONG_MAX or -LONG_MIN, the remainder is numer, carry flag is set and errno is set to:

  • [EDOM] division by zero

void _ldivu_(ldivu_t *d, unsigned long numer, unsigned long denom)

Use a single unsigned long division (numer / denom) to compute quotient and remainder and store that in the struct pointed at by d.

On division by zero, the quotient is +ULONG_MAX, the remainder is numer, carry flag is set and errno is set to:

  • [EDOM] division by zero

void _lldiv_(lldiv_t *d, long long numer, long long denom)

(nightly build, sdcc)

Use a single signed long long division (numer / denom) to compute quotient and remainder and store that in the struct pointed at by d.

On division by zero, the quotient is +LLONG_MAX or -LLONG_MIN, the remainder is numer, carry flag is set and errno is set to:

  • [EDOM] division by zero

void _lldivu_(lldivu_t *d, unsigned long long numer, unsigned long long denom)

(nightly build, sdcc)

Use a single unsigned long long division (numer / denom) to compute quotient and remainder and store that in the struct pointed at by d.

On division by zero, the quotient is +ULLONG_MAX, the remainder is numer, carry flag is set and errno is set to:

  • [EDOM] division by zero
libnew/stdlib.txt · Last modified: 2016/05/21 03:04 (external edit)