The <stdlib.h> Header File

Some useful routines proposed by ANSI (sorting, searching, etc.)

Functions

abort
Abnormal termination of a process.
abs
Absolute value of a number.
alloca
Allocates memory on the local storage space.
atexit
Registers a termination function.
atof
Converts a string to a floating point.
atoi
Converts a string to a short integer.
atol
Converts a string to a long integer.
bsearch
Binary search.
calloc
Allocates a memory block for a given number and size of items.
div
Divides two short integers, and returns quotient and remainder.
exit
Forced termination of the program.
fabs
Absolute value of a floating point number.
free
Frees an allocated block.
labs
Absolute value of a long integer number.
ldiv
Divides two long integers, and returns quotient and remainder.
malloc
Allocates a memory block.
max
Maximum of two integer numbers.
min
Minimum of two integer values.
qsort
Sorts an area of items.
rand
Returns a pseudorandom number.
random
Generates a random integer in a given range.
randomize
Initializes random number generator with a random value.
realloc
Reallocates allocated memory.
srand
Initializes random number generator.
strtod
Converts a string to a floating point value, with optional error-checking.
strtol
Converts a string to a long integer using a given radix, with detection of overflows and errors.
strtoul
Converts a string to an unsigned long integer using a given radix, with detection of overflows and errors.
TIOS_strtod

Constants

EXIT_FAILURE
Failure exit code for exit.
EXIT_SUCCESS
Normal exit code for exit.
NULL
A null-pointer value.
RAND_MAX
Returns the largest number returned by rand.

Predefined Types

atexit_t
Describes an exit function passed to atexit.
compare_t
Describes a comparison function.
div_t
An integer division return type used in the div function.
ldiv_t
A long integer division return type used in the ldiv function.
size_t
A type to define sizes of strings and memory blocks.

abort

void abort (void);

Abnormal termination of a process.

abort writes a termination message ("ABNORMAL PROGRAM TERMINATION") in the status line, then aborts the program by a call to exit (passing 0 to it).

Note that the status line text will not be visible if SAVE_SCREEN is defined.


abs

any_type abs (any_type x);

Absolute value of a number.

abs returns the absolute value of a numeric argument x, which may be either an integer or a floating point value. The returned value is of the same type as the argument.

Note: abs is a smart macro compiling to open code which depends on the type of the argument.

See also: labs, fabs


atexit

short atexit (atexit_t func);

Registers a termination function.

atexit registers the function pointed to by func as an exit function. Upon normal termination of the program (including termination using the exit function), func is called just before returning to the TIOS. Each call to atexit registers another exit function. The number of function which can be registered depends on the current number of free handles. All registered termination functions are executed on a last-in, first-out basis (the last function registered is the first to be executed). atexit returns 0 on success and nonzero on failure (no space left to register the function).

Note: Termination functions are not called on abnormal termination of the program (i.e. if an error is thrown from the program).

atexit does not work with enter_ghost_space. However, if a program is already executed in the ghost space (because of ExePack compression or because it has been called from a launcher), there should not be any problems.


atoi

short atoi (const char *str);

Converts a string to a short integer.

atoi converts the string pointed to by str to integer. atoi recognizes (in the following order):

The characters must match this generic format:

[ws] [sn] [ddd]

In atoi, the first unrecognized character ends the conversion. There are no provisions for overflow in atoi (results are wrong in a case of overflow). atoi returns the converted value of the input string. If the string cannot be converted, the return value is 0. See strtol and strtoul for conversions which allow much greater flexibility.


atol

long atol (const char *str);

Converts a string to a long integer.

atol is similar to atoi, but converts the string to a long integer.


bsearch

void *bsearch (const void *Key, const void *BasePtr, unsigned short NoOfElements, unsigned short Width, compare_t cmp_func);

Binary search.

bsearch searches a table (array) of NoOfElements elements in memory, and returns the address of the first entry in the table that matches the search key. Because this is a binary search, the first matching entry is not necessarily the first entry in the table. If no match is found, bsearch returns NULL. NoOfElements gives the number of elements in the table. Width specifies the number of bytes in each table entry. BasePtr points to the base (0-th element) of the table to be sorted. Key is a pointer to the search key. cmp_func, the comparison function, accepts two arguments, elem1 and elem2, each a pointer to an entry in the table. The comparison function compares each of the pointed-to items (*elem1 and *elem2), and returns a short integer based on the result of the comparison:

Here is a complete example of usage (called "Binary Search"):

// Search integer values using a binary search.

#define USE_TI89              // Compile for TI-89
#define USE_TI92PLUS          // Compile for TI-92 Plus
#define USE_V200              // Compile for V200

#define OPTIMIZE_ROM_CALLS
#define MIN_AMS 100           // Compile for AMS 1.00 or higher
#define SAVE_SCREEN           // Save/Restore LCD Contents

#include <tigcclib.h>         // Include All Header Files

// Comparison Function
CALLBACK short int_comp(const void *a, const void *b)
{
  return (*(const short*)a) - (*(const short*)b);
}

// Main Function
void _main(void)
{
  short list[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
  short i;
  short font;
  void *p;

  font = FontGetSys();
  FontSetSys(F_4x6);
  clrscr ();
  for (i = -1; i < 11; i++) {
    p = bsearch (&i, list, sizeof(list)/sizeof(list[0]), sizeof (list[0]), int_comp);
    if (p == NULL) {
      printf ("%d not found\n", i);
    }
    else {
      printf ("%d is at index %lu\n", i, ((void *)p - (void *)list)/sizeof(list[0]));
    }
  }
  FontSetSys(font);
  ngetchx ();
}

Note: if speed matters, create a bsearch() routine in your program, and inline the comparison function and element copy/swap codes. Your routine will be significantly faster and smaller that way.

See also: qsort


div

div_t div (short numer, short denom);

Divides two short integers, and returns quotient and remainder.

div divides two integers and returns both the quotient and the remainder as a div_t type. numer and denom are the numerator and the denominator, respectively. div returns a structure whose elements are quot (the quotient) and rem (the remainder).

Note: div is an inline function, implemented using GNU C smart macros.


exit

void exit (short code);

Forced termination of the program.

exit terminates the program (it may be called from any nesting level). Before termination, any registered "exit functions" (posted with atexit) are called. ANSI proposes that exit also closes all open files. Such behaviour is not implemented here, you need to do it manually if necessary.

code is the exit status. Value of 0 (EXIT_SUCCESS) is used to indicate a normal exit. If code is nonzero (e.g. EXIT_FAILURE), an error message dialog which corresponds with code code will be displayed before exiting. Note that this is not the same as throwing error code using ER_throwVar. Throwing an error is much more a "barbaric" method for exiting from the program. Among others, by throwing an error, no registered "exit functions" will be called.


labs

long labs (long x);

Absolute value of a long integer number.

labs returns the absolute value of (long) integer argument x.

Note: labs is a built-in function in the GCC compiler itself, and it compiles to open code instead of a function call.

See also: abs, fabs


ldiv

ldiv_t ldiv (long n, long d);

Divides two long integers, and returns quotient and remainder.

ldiv divides two long integers and returns both the quotient and the remainder as a ldiv_t type. numer and denom are the numerator and the denominator, respectively. div returns a structure whose elements are quot (the quotient) and rem (the remainder).

Note: ldiv is an inline function, implemented using GNU C smart macros.


max

any_type max (any_type a, anytype b);

Maximum of two integer numbers.

max is an inline function (implemented using GNU C smart macros) which returns the greater of a and b. They may be any numeric values, either integer or floating point numbers, and they also may be pointers to the same base type. The result has the type of the argument which has greater range of possible values (e.g. if one is float and second one is long int, the result is of float type).

See also: min


min

any_type min (any_type a, anytype b);

Minimum of two integer values.

min is an inline function (implemented using GNU C smart macros) which returns the smaller of a and b. They may be any numeric values, either integer or floating point numbers, and they also may be pointers to the same base type. The result has the type of the argument which has greater range of possible values (e.g. if one is float and second one is long int, the result is of float type).

See also: max


qsort

void qsort (void *BasePtr, unsigned short NoOfElements, unsigned short Width, compare_t cmp_func);

Sorts an area of items.

qsort sorts the entries in a table by repeatedly calling the user-defined comparison function pointed to by cmp_func. BasePtr points to the base (0-th element) of the table to be sorted. NoOfElement is the number of entries in the table. Width is the size of each entry in the table, in bytes. cmp_func, the comparison function, accepts two arguments, elem1 and elem2, each a pointer to an entry in the table. The comparison function compares each of the pointed-to items (*elem1 and *elem2), and returns a short integer based on the result of the comparison:

In the comparison, the less-than symbol (<) means the left element should appear before the right element in the final, sorted sequence. Similarly, the greater-than symbol (>) means the left element should appear after the right element in the final, sorted sequence.

The ANSI standard proposes that the comparison function has to return a long integer. However, strcmp, which is frequently used as a comparison function, returns a short integer.

Note: if speed matters, create a qsort() routine in your program, and inline the comparison function and element copy/swap codes. Your routine will be significantly faster and smaller that way.

Here is a complete example of usage (called "Sort Integers"):

// Sort a list of integer values

#define USE_TI89              // Compile for TI-89
#define USE_TI92PLUS          // Compile for TI-92 Plus
#define USE_V200              // Compile for V200

#define MIN_AMS 100           // Compile for AMS 1.00 or higher
#define SAVE_SCREEN           // Save/Restore LCD Contents

#include <tigcclib.h>         // Include All Header Files

// Comparison Function
CALLBACK short int_comp(const void *a, const void *b)
{
  return (*(const short*)a) - (*(const short*)b);
}

// Main Function
void _main(void)
{
  short list[10] = {2, 9, 3, 6, 4, 2, 3, 3, 1, 5};
  int i;
  clrscr ();
  qsort (list, 10, sizeof (short), int_comp);
  for (i = 0; i < 10; i++)
    printf ("%d ", list[i]);
  ngetchx ();
}

Note that the function strcmp is ideal for string comparisons. However, its parameters are not void pointers. This may be solved using a typecast like

qsort (StringArray, NoOfStrings, LenOfEachString, (compare_t) strcmp);

See also: bsearch


rand

short rand (void);

Returns a pseudorandom number.

rand uses a linear congruential random number generator to return successive pseudorandom numbers in the range from 0 to RAND_MAX (i.e. from 0 to 32767). It returns the generated pseudorandom number.

See also: srand, randomize, random


random

short random (short num);

Generates a random integer in a given range.

random is a macro which uses rand to return a random number between 0 and (num-1).

See also: rand, srand, randomize


randomize

void randomize (void);

Initializes random number generator with a random value.

randomize initializes the random number generator with a random value (picked from the timer).

See also: rand, random, srand


srand

void srand (unsigned long seed);

Initializes random number generator.

The random number generator is reinitialized by calling srand with an argument value of 1. It can be set to a new starting point by calling srand with a given seed number (if an argument is set to seed).

See also: rand, random, randomize


strtod

AMS 2.00 or higher

double strtod(const char *str, char **endptr);

Converts a string to a floating point value, with optional error-checking.

strtod converts a string pointed to by s to a floating point value. It recognizes the following character representation of a floating point number:

It is easy to "preprocess" any string to satisfy this convention before calling strtod, by code such as the following snippet (assuming that c is a char variable, and i is an integer variable):

for (i = 0; (c = s[i]); i++)
 // Yes, the second '=' is really '=', not '=='...
  {
    if (c == '-') s[i] = 0xAD;
    if ((c|32) == 'e') s[i] = 0x95;
  }

strtod returns the converted value (BCD floating-point number). If endptr is not NULL, the char pointer pointed to by it is assigned the address of the first character of the string following the converted floating-point number. If the conversion fails, 0.0 is returned and *endptr is assigned the value str.
If the result of the conversion would cause overflow, strtod sets errno to ERANGE and returns 9.9999999999999e+999. If the result of the conversion would cause underflow, strtod sets errno to ERANGE and returns 0.

Note: This function is part of AMS, but it is wrapped in the library to prevent a crash when end_ptr == NULL on early AMS 2.xx versions. In fact, atof ends up calling strtod, and using atof takes up more space into your program than strtod does, while not providing the endptr argument, which helps for error checking.

See also: atof, TIOS_strtod


strtol

long strtol (const char *str, char **endptr, short radix);

Converts a string to a long integer using a given radix, with detection of overflows and errors.

strtol converts a character string str to a long integer value. str is a sequence of characters that can be interpreted as a long value. The characters must match this generic format:

[ws] [sn] [0] [x] [ddd]

where

strtol stops reading the string at the first character it doesn't recognize.

The characters are interpreted according to the following table:

Value in str meant to be interpreted as Resulting Character Recognition
Octal Any character other than 0 to 7 will be unrecognized.
Decimal Any character other than 0 to 9 will be unrecognized.
A number in any other base Only the numerals and letters used to represent numbers in that base will be recognized (for example, if radix equals 5, only 0 to 4 will be recognized; if radix equals 20, only 0 to 9 and A to J will be recognized).

If endptr is not NULL, strtol sets the pointer variable pointed to by endptr to point to the character that stopped the scan (i.e. *endptr = &stopper). strtol returns the value of the converted string, or 0 on error. In a case of overflow, strtol returns LONG_MAX or LONG_MIN, depending of the sign.

Note: strtol is much more flexible than atol (or atoi), but as it is not built-in in the TIOS, usage of it makes the total size of the program much greater.


strtoul

unsigned long strtoul (const char *str, char **endptr, short radix);

Converts a string to an unsigned long integer using a given radix, with detection of overflows and errors.

strtoul operates the same way as strtol, except that it converts a string str to an unsigned long value (where strtol converts to a long). See strtol for more information. In a case of overflow, strtoul returns ULONG_MAX.


TIOS_strtod

AMS 2.00 or higher

double TIOS_strtod(const char *str, char **endptr);

You really should use strtod, unless you know what you, and your users, are doing.
This is the direct system call, which will usually take less space in your program than the library routine for strtod. But if you use it on AMS 1.00-2.03, never pass NULL as endptr, otherwise the routine will trigger a crash !

See also: strtod


EXIT_FAILURE

#define EXIT_FAILURE 1

Failure exit code for exit.

EXIT_FAILURE is a constant (here with value 1) which is usually defined in stdlib.h. Its meaning is "the exit code upon failure for exit".


EXIT_SUCCESS

#define EXIT_SUCCESS 0

Normal exit code for exit.

EXIT_SUCCESS is a constant (here with value 0) which is usually defined in stdlib.h. Its meaning is "the exit code upon success for exit".


RAND_MAX

#define RAND_MAX 32767

Returns the largest number returned by rand.

RAND_MAX is a constant (here with value 32767) which is usually defined in stdlib.h. Its meaning is "the largest number returned by rand".


atexit_t

typedef CALLBACK void (*atexit_t) (void);

Describes an exit function passed to atexit.

atexit_t is a type proposed in ANSI C for defining the type of an exit function passed to atexit.


compare_t

typedef CALLBACK short (*compare_t) (const void *elem1, const void *elem2);

Describes a comparison function.

compare_t is a type for defining the type of a comparison function passed to bsearch or qsort.

Note that this type is not ANSI-compliant: It should have a 'long' return value. The reason it does not is that the strcmp function, frequently cast to this type, returns a 'short' value.


div_t

typedef struct {
short quot, rem;
} div_t;

An integer division return type used in the div function.


ldiv_t

typedef struct {
long quot, rem;
} ldiv_t;

A long integer division return type used in the ldiv function.


Return to the main index