c++笔记4 new 和 Delete

new和malloc的区别是什么?

  • malloc和free, 称作C的库函数
  • new和delete是运算符
  • malloc开辟内存失败,通过返回值和nullptr来判断,而new开辟内存失败,是通过抛出bad_alloc类型的异常来判断的
  • malloc是按照字节开辟的,需要对返回值进行类型的转换
  • new是指定类型开辟内存的,不仅开辟内存还能给定初始值
  • new 开辟的内存区域是一个连续的内存空间,用来存储指定数量的同类型数据。为了引用这个内存空间,需要使用一个指针变量来存储内存的首地址,从而访问这个内存空间中的元素。因此,把 new 开辟出来的内存赋给一个指针变量是一种常见的做法
#include <iostream>
#include <new> // bad_alloc

int main()
{
    // 使用 malloc 分配内存
    int *p = (int *)malloc(sizeof(int));
    if (p == nullptr)
    {
        std::cerr << "Memory allocation failed using malloc" << std::endl;
        return -1;
    }
    *p = 10; // 初始化分配的内存
    std::cout << "Value allocated by malloc: " << *p << std::endl;

    // 使用 new 分配内存
    int *p1 = nullptr;
    try
    {
        int *p1 = new int(20); // 初始化为 20
        std::cout << "Value allocated by new: " << *p1 << std::endl;
    }
    catch (const std::bad_alloc &e)
    {
        std::cerr << "Memory allocation failed using new: " << e.what() << std::endl;
        free(p); // 释放 malloc 分配的内存
        return -1;
    }

    // 清理资源
    free(p); // 释放 malloc 分配的内存
    delete p1; // 释放 new 分配的内存

    return 0;
}

2. 开辟数组

2.1 c 数组

int main()
{
    // C中开辟数组内存
    int *q = (int*)malloc(sizeof(int) * 20);

    if (q == nullptr)
    {
        return -1;
    }

    free (q);
    return 0;
}

2.2 c++数组

int main()
{
    // C++中开辟数组内存
    int *q = new int[20]; // 没有初始值数组内存
    int *q1 = new int[20](); // 全部初始化为0

    delete []q;
    delete []q1;
    return 0;
}

posted @ 2025-04-23 17:25  qinchaojie  阅读(10)  评论(0)    收藏  举报  来源