c++ - 使用 C++ 动态分配结构数组

标签 c++ new-operator struct

我的问题是我有一个类,它应该使用一个名为“size”的 long int,并使用它来动态创建一个结构数组。以下编译,但我收到一个运行时错误,内容如下:

错误“在抛出 'std::bad_alloc' what() 实例后调用终止:std::bad_alloc 中止

struct PageEntry
{
    ..some stuff in here
};

class PageTable {
public:
    PageTable(); //Default PageTable constructor.
    PageTable(long int size); //PageTable constructor takes arrival time and execution time as parameter
    ~PageTable(); //PageTable destructor.
    PageEntry *pageArray;
};

PageTable::PageTable(long int size)
{
    cout << "creating array of page entries" << endl;
    pageArray = new PageEntry[size];   //error occurs here
    cout << "done creating" << endl;
}

如果我用数字替换“大小”,即不会发生错误。 10000. 有什么想法吗?

最佳答案

我的猜测是,当您调用函数 size 时,不知何故最终变成了一个大得离谱的数字或负数。尝试在函数内部打印出来并告诉我们它是什么。您可能内存不足。

另外,停止使用 endl 除非你特意用它来代替 '\n'

关于c++ - 使用 C++ 动态分配结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5347392/

相关文章:

C 程序接收信号 SIGTRAP,每 3 次尝试运行良好

c++11 - 将 C++ 程序移植到 Rust : Of reinterpret_cast, 结构和蓝牙

c++ - 在 vs 2003 上将管道(处理程序)转换为 fd 时出错

c++ - warpPerspective 和 perspectiveTransform 有什么区别?

python - __getattr__ 的不对称行为,新式与旧式类

c++ - 使用预分配的内存和数组管理析构函数

javascript - 我们可以在使用 "new"运算符创建对象时省略括号吗?

C++ - 你应该用一个常规数组来调整大小吗?

c++ - 在 C/C++ 中将数据从一个文件复制到另一个文件的最快方法?

f# - address-of 和 ref 运算符之间的差异