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

malloc

需要头文件  #include

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函数。其次,参数里是需要开辟的字节

c/c++ malloc、calloc、realloc and free_第1张图片

calloc

需要头文件  #include

函数原型:

void *calloc( size_t num, size_t size );

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

c/c++ malloc、calloc、realloc and free_第2张图片

realloc

需要头文件  #include

函数原型:

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种情况

空间足够大:

c/c++ malloc、calloc、realloc and free_第3张图片

空间不够:

c/c++ malloc、calloc、realloc and free_第4张图片

free

函数原型:

void free( void *memblock );

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

c/c++ malloc、calloc、realloc and free_第5张图片

常见错误 :

1、对NULL指针的非法访问

c/c++ malloc、calloc、realloc and free_第6张图片

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

 c/c++ malloc、calloc、realloc and free_第7张图片

 

2、越界访问

c/c++ malloc、calloc、realloc and free_第8张图片

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

c/c++ malloc、calloc、realloc and free_第9张图片

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

c/c++ malloc、calloc、realloc and free_第10张图片

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

c/c++ malloc、calloc、realloc and free_第11张图片

你可能感兴趣的:(c语言,开发语言)