C++ 变量不再存在

标签 c++ memory memory-leaks

#include <exception>
#include <iostream>
#include <cstdio>

using namespace std;

class BaseException : exception {
public:
    BaseException(const char* message) : message(message) {}
    const char* getMessage() {
        return message;
    }
private:
    const char* message;
};

void wrong() {
    unsigned short int argumentCallCounter = 1;

    /// @todo check why commented below does not work ?!
    // char tmp[13 + sizeof(argumentCallCounter)];

    /// @todo but this works
    char* tmp = new char[13 + sizeof(argumentCallCounter)];
    sprintf(tmp, "No %u argument", argumentCallCounter);

    throw BaseException(tmp);
}

int main(int argc, char** argv) {
    try {
        wrong();
    } catch (BaseException e) {
        cout << e.getMessage() << endl;
    }

    return 0;
}

上面的代码有效,但是在注释中,有一段代码不起作用。
char tmp[13 + sizeof(argumentCallCounter)];
我知道它不起作用,因为当程序离开函数 错误 时,变量 tmp 不再存在。
有人可以帮忙吗?

还有我写的那个决定:
char* tmp = new char[13 + sizeof(argumentCallCounter)];
这也不好,因为当程序完成时,内存泄漏,因为没有人删除 tmp

最佳答案

我通常抛出一个用 std::string 初始化的 std::runtime_exception。

关于C++ 变量不再存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5659738/

相关文章:

c++ - Boost Spirit模板特化失败

c++ - Boost 线程失败 BOOST_ASSERT( px != 0 );

macos - 如何限制 OS X 程序的内存? ulimit -v 都不 -m 工作

c - 二叉搜索树插入导致内存泄漏

c++ - C++ 中的纯虚函数在哪里?

c++ - C++ 中的自减运算符

ios - 两个带有数据的 TableView ,并希望从一个特定的 TableView 中删除索引。我还必须删除另一个数组吗?

c - 内存映射显示的 RAM 多于物理可用的 RAM

memory-leaks - PipelineBuffer 不释放内存

ios - 泄漏内存工具在分配属性时无法检测到泄漏,那么,泄漏内存是否是泄漏内存?