malloc是什么意思呢?怎么用?

来源:百度知道 编辑:UC知道 时间:2024/05/30 01:06:17
如题,小虾向高手指教``!

  1. malloc函数向系统申请分配指定size个字节的内存空间。返回类型是 void* 类型。void* 表示未确定类型的指针。C,C++规定,void* 类型可以强制转换为任何其它类型的指针。

  2. 函数声明:void *malloc(size_t size),void* 表示未确定类型的指针,void *可以指向任何类型的数据,更明确的说是指申请内存空间时还不知道用户是用这段空间来存储什么类型的数据。

  3. malloc函数的实质体现在,它有一个将可用的内存块连接为一个长长的列表的所谓空闲链表。调用malloc函数时,它沿连接表寻找一个大到足以满足用户请求所需要的内存块。然后,将该内存块一分为二(一块的大小与用户请求的大小相等,另一块的大小就是剩下的字节)。接下来,将分配给用户的那块内存传给用户,并将剩下的那块(如果有的话)返回到连接表上。

函数名: malloc
功 能: 内存分配函数
用 法: void *malloc(unsigned size);
程序例:
#include
#include
#include
#include
int main(void)
{
char *str;
/* allocate memory for string */
/* This will generate an error when compiling */
/* with C++, use the new operator instead. */
if ((str = malloc(10)) == NULL)
{
printf("Not enough memory to allocate buffer\n");
exit(1); /* terminate program if out of memory */
}
/* copy "Hello" into string */