malloc是动态存储函数。malloc分配一块内存,在参数中指定所包含的字节数。它将void指针返回给所分配的存储的第一个字节。不初始化所分配的存储。
malloc函数的头文件有两个,<stdlib.h>或<malloc.h>.这两个都可以。
malloc函数的原型:extern void*(unsigned int num_bytes)。
功能:分配长度为num_bytes字节的内存块。
返回值:如果分配成功则返回指向被分配内存的指针,否则返回空指针NULL。在MSDN中的解释(如果英文不好的话,可以用有道词典):
malloc returns a void pointer to the allocated space, or NULL if there is insufficient memory available. To return a pointer to a type other than void, use a type cast on the return value. The storage space pointed to by the return value is guaranteed to be suitably aligned for storage of any type of object. If size is 0, malloc allocates a zero-length item in the heap and returns a valid pointer to that item. Always check the return from malloc, even if the amount of memory requested is small.
malloc返回值的类型是void*类型。void*类型表示未确定的指针类型,也可以称为任意类型。在使用它是可以用强制类型转换将其转换成其他类型的指针。
注意:当不再使用内存时应该用free()函数将内存释放掉
例如:
- /*声明一个指针*/
- int *pointer;
- /*分配128个整型存储单元,
- 并将这128个连续的整型存储的首地址存储到指针变量pointer中
- 数据类型可根据具体的需要而确定*/
- pointer = (int *)malloc(sizeof(int)*128);
顺便说一下,为了便于移植,malloc函数通过sizeof操作符来指定数据类型的大小。如果写成int* pointer=(int*)malloc(1);虽然编译能够通过,但是它只分配了一个字节大小的内存空间。当存入一个整型数据时,就会有3个字节无法分配空间,这样容易造成数据的丢失。请特别注意这一点。
完整的程序:
- /* MALLOC.C: This program allocates memory with
- * malloc, then frees the memory with free.
- */
- #include <stdio.h>
- #include <malloc.h>
- void main( void )
- {
- char *string;
- /* Allocate space for a path name */
- string = malloc( _MAX_PATH );
- if( string == NULL )
- printf( "Insufficient memory available\n" );
- else
- {
- printf( "Memory space allocated for path name\n" );
- free( string );
- printf( "Memory freed\n" );
- }
- }
- Output
- Memory space allocated for path name
- Memory freed