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

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、对同一块内存空间进行多次释放

  • 29
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
malloccallocrealloc和new都是C++和C语言中动态分配内存时经常用到的函数。它们之间的区别如下: 1. malloc malloc是C语言中最基本的动态内存分配函数。它需要传入分配内存空间的大小,并返回分配空间的首地址。malloc分配内存时,只是在内存空间中找到大小合适的连续空闲区域,然后将该内存块标记为已用状态。使用完毕后,需要手动调用free()函数来释放所分配的内存空间,否则将会造成内存泄漏。 2. calloc callocmalloc类似,它也是用来分配内存的。calloc需要传入分配内存空间的大小和空间个数,并返回分配空间的首地址。calloc分配出来的内存空间是没有被初始化的,即内存中的每一位都被初始化为0。使用完毕后,同样需要调用free()函数来释放空间。 3. realloc realloc是C/C++中用来重新调整内存大小的函数。它需要传入要调整内存的地址和要调整的大小。如果新的内存大小比原来的内存大小小,则realloc将原有内存块缩小为新的大小,多余的空间将释放;如果新的内存大小比原来的内存大小大,则需要重新分配一块内存,将原有内存块的数据拷贝到新的内存块中,并释放原有内存块。使用完毕后,仍需要调用free()函数来释放内存。 4. new new是C++中的动态内存分配方式,它是一个运算符,不是一个函数。new可以分配任意类型的内存空间,包括基本类型、类、结构体等。使用new分配内存后,不需要手动释放内存,因为C++中有自动的内存回收机制。如果使用new分配的空间已经不需要使用,C++会自动调用delete或delete[]来释放内存。 总的来说,malloccallocrealloc和new都是动态内存分配的方式,它们的使用场景不同,需要根据具体情况选择使用。在使用完毕后,都需要手动或自动释放内存,以避免内存泄漏的问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值