malloc ()- 保留存储块

格式

#include <stdlib.h>
void *malloc(size_t size);

语言级别

ANSI

线程安全

描述

malloc() 函数保留 size 字节的存储块。 与 calloc() 函数不同, malloc() 不会将所有元素初始化为 0。 非太字节空间 malloc() 的最大大小为 16711568 字节。

注:
  1. 所有堆存储器都与调用函数的激活组相关联。 因此,应该在同一激活组中分配,取消分配和重新分配存储器。 不能在一个激活组中分配堆存储器,也不能从另一个激活组中取消分配或重新分配该存储器。 有关激活组的更多信息,请参阅 ILE 概念 手册。
  2. 要在不更改 C 源代码的情况下使用 太字节空间 存储器而不是单层存储器,请在编译器命令上指定 TERASPACE (*YES *TSIFC) 参数。 这会将 malloc() 库函数映射到 _C_TS_malloc()(其太字节空间存储器对等项)。 每次调用 _C_TS_malloc() 可分配的最大太字节空间存储量为 2GB -224 或 2147483424 字节。 如果单个请求需要超过 2147483408 字节,请调用 _C_TS_malloc64(unsigned long long int);

    有关更多信息,请参阅 ILE 概念 手册。

  3. 要获取有关激活组中 MI 程序正在使用的太字节空间存储器的当前统计信息,请调用 _C_TS_malloc_info 函数。 此函数返回信息,包括总字节数,已分配的字节数和块数,未分配的字节数和块数,请求的字节数,填充字节数和开销字节数。 要获取有关 _C_TS_malloc() _C_TS_malloc64() 函数所使用的内存结构的更多详细信息,请调用 _C_TS_malloc_debug() 函数。 您可以使用此函数返回的信息来识别内存损坏问题。
  4. 如果已在当前激活组中启用快速池内存管理器,那么将使用快速池内存管理器检索存储器。 请参阅 _C_Quickpool_Init ()-初始化快速池内存管理器 以获取更多信息。

返回值

malloc() 函数返回指向保留空间的指针。 返回值所指向的存储空间适合用于存储任何类型的对象。 如果没有足够的可用存储器,或者如果将 size 指定为零,那么返回值为 NULL

示例

此示例提示输入所需的数组条目数,然后在存储器中为这些条目保留足够的空间。 如果 malloc() 成功,那么示例会将值分配给条目并打印出每个条目; 否则,会打印出错误。
#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
  long * array;    /* start of the array */
  long * index;    /* index variable     */
  int    i;        /* index variable     */
  int  num;        /* number of entries of the array */
 
  printf( "Enter the size of the array\n" );
  scanf( "%i", &num );
 
  /* allocate num entries */
  if ( (index = array = (long *) malloc( num * sizeof( long ))) != NULL )
  {
 
    for ( i = 0; i < num; ++i )           /* put values in array    */
       *index++ = i;                      /* using pointer notation */
 
    for ( i = 0; i < num; ++i )           /* print the array out    */
      printf( "array[ %i ] = %i\n", i, array[i] );
  }
  else { /* malloc error */
    perror( "Out of storage" );
    abort();
  }
}
 
/********************  Output should be similar to:  **************
 
Enter the size of the array
array[ 0 ] = 0
array[ 1 ] = 1
array[ 2 ] = 2
array[ 3 ] = 3
array[ 4 ] = 4
*/

相关信息