牛骨文教育服务平台(让学习变的简单)
博文笔记

C/C++——C和C++怎样分配和释放内存,区别是什么?

创建时间:2015-12-28 投稿人: 浏览次数:823

C语言分配内存的函数:

#include <stdlib.h>
void *malloc(size_t size);
void *calloc(size_t nmemb, size_t size);
void *realloc(void *ptr, size_t size);

malloc函数分配大小为size字节的内存空间,返回一个指针指向申请的该内存的首地址,该内存区域没有被初始化。
calloc函数分配大小为nmemb*size字节的内存空间(nmemb是数据的大小,size是每个数据的大小),返回一个指针指向申请的该内存的首地址,该内存区域被初始化为0。
realloc函数改变之前ptr指向的内存的大小。重新分配大小为size字节的内存空间,返回一个指针指向申请的该内存的首地址。

C语言释放内存的函数:

#include <stdlib.h>
void free(void *ptr);
free用来释放由malloc,calloc,realloc分配的内存,free的参数是它们三个函数的返回值(指向动态内存的指针);

下面是man手册对这四个函数详细讲解:(可以自己查一下:在终端输入命令man malloc然后就出现了这四个函数的介绍)

The malloc() function allocates size bytes and returns a pointer to the allocated memory.  The memory is not initialized.  If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc().  Otherwise, or  if free(ptr) has already been called before, undefined behavior occurs.  If ptr is NULL, no operation is performed.

The  calloc()  function allocates memory for an array of nmemb elements of size bytes each and returns a pointer to the allocated memory.  The memory is set to zero.If nmemb or size is 0, then calloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

The realloc() function changes the size of the memory block pointed to by ptr to size bytes.  The contents will be unchanged in the  range  from  the  start  of  the region  up to the minimum of the old and new sizes.  If the new size is larger than the old size, the added memory will not be initialized.  If ptr is NULL, then the call is equivalent to malloc(size), for all values of size; if size is equal to zero, and ptr is not NULL, then the call is equivalent to free(ptr).  Unless  ptr  is NULL, it must have been returned by an earlier call to malloc(), calloc() or realloc().  If the area pointed to was moved, a free(ptr) is done.

C++用new来分配内存,用delete来释放内存。

1、申请单个对象,比如int对象(变量)
int *p = new int;

int *p = new int(100);
2、申请数组
int *p = new int[100];
3、释放单个对象
delete p;
4、释放数组
delete [] p;

实例:

#include<iostream>
using namespace std;

int main()
{
    int *p = new int;
    *p = 99;
    cout << "*p is " << *p << endl;
    int *p2 = new int(100);
    cout << "*p2 is " << *p2 << endl;

    int  *parray = new int[10];
    cout <<"申请一个int数组,大小为10,内存已经初始化为0了,现在打印这十个初始化的数值
";
    for (int i = 0; i < 10; i++){
        cout << *(parray+i) << ", ";
    }
    cout << endl;

    cout << "释放内存p
";
    delete p;
    cout << "释放内存p2
";
    delete p2;
    cout << "释放该int数组
";
    delete [] parray;

    return 0;
}


两者的区别:

1、new和delete是C++动态申请内存和释放内存的运算符,不是一个标准库中的函数。

2、new分配的对象会调用析构函数,malloc分配的是一块内存区域。


推荐一个链接:

http://www.nowamagic.net/librarys/veda/detail/2427

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。