温馨提示×

C++ Linux下如何进行内存分配

小樊
38
2025-12-05 02:24:50
栏目: 编程语言

在Linux下使用C++进行内存分配,主要有以下几种方式:

1. 栈上分配(栈内存)

栈内存是由编译器自动管理的,当函数调用时,局部变量会被分配在栈上。

void exampleFunction() {
    int stackVar; // 栈上分配
    stackVar = 10;
}

2. 堆上分配(堆内存)

堆内存是通过newdelete(或mallocfree)手动管理的。

使用 newdelete

#include <iostream>

int main() {
    int* heapVar = new int; // 堆上分配
    *heapVar = 10;
    std::cout << "Heap variable: " << *heapVar << std::endl;
    delete heapVar; // 释放堆内存
    return 0;
}

使用 mallocfree

#include <iostream>
#include <cstdlib> // 包含 malloc 和 free

int main() {
    int* heapVar = (int*)malloc(sizeof(int)); // 堆上分配
    if (heapVar == nullptr) {
        std::cerr << "Memory allocation failed!" << std::endl;
        return 1;
    }
    *heapVar = 10;
    std::cout << "Heap variable: " << *heapVar << std::endl;
    free(heapVar); // 释放堆内存
    return 0;
}

3. 使用智能指针

智能指针是C++11引入的一种自动管理内存的工具,可以避免手动调用delete

std::unique_ptr

#include <iostream>
#include <memory>

int main() {
    std::unique_ptr<int> uniquePtr(new int(10));
    std::cout << "Unique pointer value: " << *uniquePtr << std::endl;
    // 不需要手动 delete,uniquePtr 会在离开作用域时自动释放内存
    return 0;
}

std::shared_ptr

#include <iostream>
#include <memory>

int main() {
    std::shared_ptr<int> sharedPtr = std::make_shared<int>(10);
    std::cout << "Shared pointer value: " << *sharedPtr << std::endl;
    // 不需要手动 delete,sharedPtr 会在最后一个引用被销毁时自动释放内存
    return 0;
}

4. 使用 std::vector

std::vector 是一个动态数组,可以自动管理内存。

#include <iostream>
#include <vector>

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    for (int num : vec) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    // 不需要手动释放内存,vector 会自动管理其内部数组的内存
    return 0;
}

5. 使用 std::string

std::string 是一个字符串类,可以自动管理内存。

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, World!";
    std::cout << str << std::endl;
    // 不需要手动释放内存,string 会自动管理其内部字符数组的内存
    return 0;
}

总结

  • 栈内存:适用于局部变量,自动管理,生命周期与函数调用周期一致。
  • 堆内存:适用于需要动态分配和释放的内存,需要手动管理。
  • 智能指针:提供了一种更安全、更方便的内存管理方式。
  • 标准库容器:如 std::vectorstd::string,提供了自动内存管理功能。

选择合适的内存管理方式可以提高代码的安全性和可维护性。

0