蓝色天空.知识 · 实践 · 创造
我的收藏
C++ 教程目录 99章
课程介绍
C++ / LEARN BY DOING

C++ <cstdlib>

系统讲解 C++ 通用工具头文件 <cstdlib>(封装 <stdlib.h>):进程退出 exit/atexit、system 命令调用、malloc/realloc/free 与 C++ 对象模型差异、atoi/atof 与 strtol/strtod 对比、rand/srand、qsort/bsearch 及 abs/div。

学完这一章,你能够

  • 系统讲解 C++ 通用工具头文件 <cstdlib>(封装 <stdlib.h>):进程退出 exit/atexit、system 命令调用、malloc/realloc/free 与 C++ 对象模型差异、atoi/atof 与 strtol/strtod 对比、rand/srand、qsort/bsearch 及 abs/div。

<cstdlib> 概述与核心通用工具函数

`<cstdlib>` 封装自 C 标准库 `<stdlib.h>`,汇集了进程控制(`std::exit`、`std::atexit`、`std::abort`、`EXIT_SUCCESS`/`EXIT_FAILURE`)、外部命令与环境变量(`std::system`、`std::getenv`)、C 风格原始堆内存分配(`std::malloc`/`std::calloc`/`std::realloc`/`std::free`)、字符串数值转换(`std::atoi`/`std::atof`/`std::strtol`/`std::strtod`)、传统伪随机(`std::rand`/`std::srand`)以及 `std::qsort`/`std::bsearch`/`std::abs`/`std::div` 等通用工具。

进程控制 exit/system 与原始内存 malloc/free

`std::exit(status)` 会立即结束当前进程并返回退出码(推荐 `EXIT_SUCCESS` 或 `EXIT_FAILURE`),期间会逆序调用 `std::atexit()` 注册的清理函数、销毁静态存储期对象并刷新关闭所有 C 标准流;但须高度警惕:**`std::exit()` 不会展开调用栈,也不会调用任何局部自动变量的析构函数**,因此在现代 C++ 中应尽量从 `main()` 正常 `return` 而非在深层函数直接调用 `exit()`。`std::system(cmd)` 将命令字符串交给宿主 Shell 执行(例如 Windows 下的 `dir`、Linux 下的 `ls`;传入 `nullptr` 可探测 Shell 是否可用),存在严重的平台耦合与命令注入安全风险,切勿拼接不可信用户输入。

`std::malloc(bytes)` 从堆申请未初始化的原始字节块,`std::realloc` 可调整块大小,使用完毕必须以 `std::free(ptr)` 归还(在 C++ 中必须将 `void*` 显式转型如 `static_cast<int*>`,并始终判空)。需要牢记:`malloc`/`free` **不会调用 C++ 构造函数与析构函数**,严禁与 `new`/`delete` 混用;除对接 C ABI 外,C++ 代码应优先选用 `std::vector` 与智能指针。

字符串数值转换、传统 rand/srand 与现代替代建议

`std::atoi("123")` 与 `std::atof("456.78")` 能快速把 C 字符串转为 `int` 与 `double`,但它们**无法区分非法输入与 `0`**,且整数溢出时直接触发未定义行为。生产代码应改用支持 `endptr` 与 `errno` 诊断的 `std::strtol`/`std::strtod`、`<string>` 中的 `std::stoi`/`std::stod`,或 C++17 `<charconv>` 中的无分配零开销 `std::from_chars`。

`std::srand(seed)` 为全局伪随机发生器设种(常见示例用 `std::time(nullptr)`),随后 `std::rand() % 100` 生成 `[0, 99]` 整数。然而 `rand()` 周期短、共享全局非线程安全状态且取模存在均匀性偏差,现代 C++ 强烈建议改用 `<random>` 头文件中的 `std::mt19937` 与 `std::uniform_int_distribution`。

实测 <cstdlib> malloc/realloc/free、atoi/strtol、srand/rand/qsort/bsearch 与 exit/system 探针

含完整源码 · 132 行
展开查看收起
cpp
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>

namespace lab {

struct Case {
    std::string name;
    std::string expected_json;
    std::string actual_json;
    bool passed;
};

std::string esc(const std::string& s) {
    std::string out = "\"";
    for (unsigned char c : s) {
        switch (c) {
            case '\"': out += "\\\""; break;
            case '\\': out += "\\\\"; break;
            case '\n': out += "\\n"; break;
            case '\r': out += "\\r"; break;
            case '\t': out += "\\t"; break;
            default:
                if (c < 0x20) {
                    char buf[8];
                    std::snprintf(buf, sizeof(buf), "\\u%04x", c);
                    out += buf;
                } else {
                    out += static_cast<char>(c);
                }
        }
    }
    out += "\"";
    return out;
}

std::string jbool(bool v) { return v ? "true" : "false"; }

void emit(const std::vector<Case>& cases) {
    std::cout << "{\"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\", \"cases\": [";
    for (std::size_t i = 0; i < cases.size(); ++i) {
        if (i) std::cout << ", ";
        std::cout << "{\"name\": " << esc(cases[i].name)
                  << ", \"expected\": " << cases[i].expected_json
                  << ", \"actual\": " << cases[i].actual_json
                  << ", \"passed\": " << jbool(cases[i].passed) << "}";
    }
    std::cout << "]}\n";
}

} // namespace lab

namespace {

int cmp_int(const void* a, const void* b) {
    int va = *static_cast<const int*>(a);
    int vb = *static_cast<const int*>(b);
    return (va > vb) - (va < vb);
}

void noop_exit_handler() {}

} // namespace

int main() {
    std::vector<lab::Case> cases;

    // Case 1: malloc / realloc / free dynamic buffer management
    int* ptr = static_cast<int*>(std::malloc(10 * sizeof(int)));
    bool c1 = false;
    if (ptr != nullptr) {
        int sum = 0;
        for (int i = 0; i < 10; ++i) {
            ptr[i] = i * i;
            sum += ptr[i];
        }
        int* grown = static_cast<int*>(std::realloc(ptr, 12 * sizeof(int)));
        if (grown != nullptr) {
            ptr = grown;
            ptr[10] = 100;
            ptr[11] = 121;
            c1 = (sum == 285) && (ptr[9] == 81) && (ptr[11] == 121);
        }
        std::free(ptr);
    }
    cases.push_back({"malloc_calloc_realloc_free", lab::jbool(true), lab::jbool(c1), c1});

    // Case 2: atoi / atof vs safer strtol / strtod with endptr validation
    int n1 = std::atoi("123");
    double d1 = std::atof("456.78");
    char* end_i = nullptr;
    long n2 = std::strtol("255abc", &end_i, 10);
    char* end_d = nullptr;
    double d2 = std::strtod("3.5xyz", &end_d);
    bool c2 = (n1 == 123) && (std::fabs(d1 - 456.78) < 1e-9) &&
              (n2 == 255 && end_i != nullptr && *end_i == 'a') &&
              (std::fabs(d2 - 3.5) < 1e-9 && end_d != nullptr && *end_d == 'x');
    cases.push_back({"atoi_atof_and_strtol_strtod", lab::jbool(true), lab::jbool(c2), c2});

    // Case 3: srand / rand reproducibility + qsort / bsearch + abs / div
    std::srand(12345u);
    std::vector<int> seq1(5);
    for (int& v : seq1) v = std::rand() % 100;
    std::srand(12345u);
    std::vector<int> seq2(5);
    for (int& v : seq2) v = std::rand() % 100;

    int arr[5] = {42, 7, 19, 3, 25};
    std::qsort(arr, 5, sizeof(int), cmp_int);
    int key = 19;
    int* found = static_cast<int*>(std::bsearch(&key, arr, 5, sizeof(int), cmp_int));
    std::div_t qr = std::div(23, 5);
    bool c3 = (seq1 == seq2) && (arr[0] == 3 && arr[4] == 42) &&
              (found != nullptr && *found == 19) &&
              (std::abs(-42) == 42) && (qr.quot == 4 && qr.rem == 3);
    cases.push_back({"srand_rand_and_qsort_bsearch", lab::jbool(true), lab::jbool(c3), c3});

    // Case 4: EXIT_SUCCESS / EXIT_FAILURE, atexit registration, system(nullptr), getenv
    int reg_rc = std::atexit(noop_exit_handler);
    int shell_avail = std::system(nullptr);
    const char* path_env = std::getenv("PATH");
    bool c4 = (EXIT_SUCCESS == 0) && (EXIT_FAILURE != 0) &&
              (reg_rc == 0) && (shell_avail != 0) && (path_env != nullptr);
    cases.push_back({"exit_constants_and_system_probe", lab::jbool(true), lab::jbool(c4), c4});

    lab::emit(cases);
    return 0;
}
验证 malloc/realloc 写入与释放、atoi/atof 及 strtol/strtod 尾指针校验、固定种子 rand 复现与 qsort/bsearch/abs/div,以及 EXIT 常量、atexit、system(nullptr) 和 getenv。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a2307.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:C++

课程关联工程包(登记关联99章) · 含当前章节或实例 · mbskycom202612a2307.zip

下载课程关联工程包:C++

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2343.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

从 `main()` 执行 `return 0;` 会先按逆序销毁 `main()` 内的所有局部自动对象(执行 RAII 析构释放锁、文件与内存),再销毁静态对象;而直接调用 `std::exit(0)` 不会展开栈帧,局部对象的析构函数不会被调用。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习