(libc.info.gz) Basic Allocation

Info Catalog (libc.info.gz) Unconstrained Allocation (libc.info.gz) Malloc Examples
 
 3.2.2.1 Basic Memory Allocation
 ...............................
 
 To allocate a block of memory, call 'malloc'.  The prototype for this
 function is in 'stdlib.h'.
 
  -- Function: void * malloc (size_t SIZE)
      Preliminary: | MT-Safe | AS-Unsafe lock | AC-Unsafe lock fd mem |
       POSIX Safety Concepts.
 
      This function returns a pointer to a newly allocated block SIZE
      bytes long, or a null pointer if the block could not be allocated.
 
    The contents of the block are undefined; you must initialize it
 yourself (or use 'calloc' instead;  Allocating Cleared Space).
 Normally you would cast the value as a pointer to the kind of object
 that you want to store in the block.  Here we show an example of doing
 so, and of initializing the space with zeros using the library function
 'memset' ( Copying and Concatenation):
 
      struct foo *ptr;
      ...
      ptr = (struct foo *) malloc (sizeof (struct foo));
      if (ptr == 0) abort ();
      memset (ptr, 0, sizeof (struct foo));
 
    You can store the result of 'malloc' into any pointer variable
 without a cast, because ISO C automatically converts the type 'void *'
 to another type of pointer when necessary.  But the cast is necessary in
 contexts other than assignment operators or if you might want your code
 to run in traditional C.
 
    Remember that when allocating space for a string, the argument to
 'malloc' must be one plus the length of the string.  This is because a
 string is terminated with a null character that doesn't count in the
 "length" of the string but does need space.  For example:
 
      char *ptr;
      ...
      ptr = (char *) malloc (length + 1);
 
  Representation of Strings, for more information about this.
 
Info Catalog (libc.info.gz) Unconstrained Allocation (libc.info.gz) Malloc Examples
automatically generated by info2html