Allocates memory blocks.
void *malloc( size_t size );The size_ttypedef is an unsigned int size : to allocate.. Return Value:malloc returns a void pointerto 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 frommalloc, even if the amount of memory requested is small.
Deallocates or frees a memory block.
void free( void *memblock );memblock:Previously allocated memory block to be freed.
Thefreefunction deallocates a memory block (memblock) that was previously allocated by a call tocalloc,malloc, orrealloc. The number of freed bytes is equivalent to the number of bytes requested when the block was allocated (or reallocated, in the case ofrealloc). IfmemblockisNULL, the pointer is ignored andfreeimmediately returns. Attempting to free an invalid pointer (a pointer to a memory block that was not allocated bycalloc,malloc, orrealloc) may affect subsequent allocation requests and cause errors.
-----------------------------------------------------------------------------------------------------------------
void *malloc(long NumBytes):该函数分配了NumBytes个,并返回了指向这块内存的指针。如果
分配失败,则返回一个空指针(NULL)。
关于分配失败的原因,应该有多种,比如说空间不足就是一种。
void free(void *FirstByte): 该函数是将之前用malloc分配的空间还给程序或者是操作系统,也就
是释放了这块内存,让它重新得到自由。
-------------------------------------------------------------------------------------------------------------------
原型:extern void *malloc(unsigned int num_bytes);
用法:#include <malloc.h>
或#include<stdlib.h>
功能:分配长度为num_bytes字节的内存块
说明:如果分配成功则返回指向被分配内存的指针,否则返回空指针NULL。
当内存不再使用时,应使用free()函数将内存块释放。
malloc的语法是:指针名=(数据类型*)malloc(长度),(数据类型*)表示指针.
本文详细介绍了内存分配与释放的基本函数malloc和free的使用方法,包括它们的参数、返回值及常见错误处理。同时,解释了如何正确地管理内存资源,避免内存泄漏,提升程序性能。

1万+

被折叠的 条评论
为什么被折叠?



