1 函数原型
malloc():分配内存块,函数原型如下:
void* malloc (size_t size);
cstdlib库描述如下:
Allocate memory block
1. Allocates a block of size bytes of memory, returning a pointer to the beginning of the block.
2. The content of the newly allocated block of memory is not initialized, remaining with indeterminate values.
3. If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be dereferenced.
- malloc()函数:
(1)用于向系统申请分配size个字节的内存块;
(2)用于动态内存分配,允许程序在运行时根据需要分配内存; - 注意事项
(1)类型转换:应将malloc()函数返回的void*型指针转换为所需类型的指针;
(2)检查返回值:应检查malloc()函数的返回值是否为NULL,以判断内存分配是否成功;
(3)内存初始化:malloc()函数分配的内存是未初始化的,值是不确定的;
(4)内存释放:malloc()函数分配的内存使用完后,应使用free()函数释放,以避免内存泄漏;释放后,应将指针设置为NULL,防止野指针问题。
2 参数
malloc()函数只有一个参数size:
- 参数size是向系统申请分配的内存块的大小,单位为字节,类型为size_t。
cstdlib库描述如下:
size
1. Size of the memory block, in bytes.
2. size_t is an unsigned integral type.
3 返回值
malloc()函数的返回值类型为void*型:
- 分配成功,返回指向新分配的内存块的指针;
- 分配失败,返回NULL。
cstdlib库描述如下: