c/c++ malloc、calloc、realloc and free

2023-12-16 00:08:27

malloc

需要头文件? #include<stdlib.h>

void *malloc( size_t size );

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函数作用是向内存堆区申请一块连续的空间,若是申请成功,则返回一个指针,这个指针是指向这段连续空间的首地址,若是开辟空间不成功,则返回NULL指针。

需要注意的是,向堆区申请空间,都必须检测一下空间是否开辟成功,可以利用assert函数。其次,参数里是需要开辟的字节

calloc

需要头文件? #include<stdlib.h>

函数原型:

void *calloc( size_t num, size_t size );

?calloc函数跟malloc函数很像,但是唯一的区别是它会根据需求开辟一段连续的空间,然后将这段连续的空间内所有的元素置为0

realloc

需要头文件? #include<stdlib.h>

函数原型:

void *realloc( void *memblock, size_t size );

realloc returns a void pointer to the reallocated (and possibly moved) memory block. The return value is NULL if the size is zero and the buffer argument is not NULL, or if there is not enough available memory to expand the block to the given size. In the first case, the original block is freed. In the second, the original block is unchanged. The return value points to a storage space that is guaranteed to be suitably aligned for storage of any type of object. To get a pointer to a type other than void, use a type cast on the return value.

但是realloc调整新的空间有2种情况

空间足够大:

空间不够:

free

函数原型:

void free( void *memblock );

函数的参数是一个指针,这个指针是指向向系统开辟的空间后返回的首地址。

常见错误 :

1、对NULL指针的非法访问

若是直接对p进行解引用,会出现如上提示。所以解决办法是先对指针p进行判断是否为NULL,

?

?

2、越界访问

3、释放非动态内存开辟的空间

4、使用free释放动态内存空间的一部分

5、对同一块内存空间进行多次释放

文章来源:https://blog.csdn.net/weixin_42346279/article/details/134890506
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。