【问题标题】:C++ cannot allocate too big array of objects on a heapC++ 不能在堆上分配太大的对象数组
【发布时间】:2015-08-21 13:10:25
【问题描述】:

我有以下 c++ 代码(基于 Visual Studio 2013 构建):

MapGraph& MapGraph::operator= (const MapGraph& other)
{
    if (this != &other)
    {
        this->primaryCopy = false;

        this->edges = new int[other.edgeQty];
        this->pointers = new int[other.vertexQty + 1];
        this->contents = new int[other.vertexQty]();
        this->weights = new NodeWeight[other.vertexQty];

数组:edgespointerscontents 的创建没有问题。但是当涉及到 weights 创建时,它会抛出没有任何信息的异常。异常发生在newaop.cpp(不是我的项目文件):

// newaop -- operator new[](size_t) REPLACEABLE
#include <new>

void *__CRTDECL operator new[](size_t count) _THROW1(std::bad_alloc)
    {   // try to allocate count bytes for an array
    return (operator new(count));
    }

/*
 * Copyright (c) 1992-2007 by P.J. Plauger.  ALL RIGHTS RESERVED.
 * Consult your license regarding permissions and restrictions.
 V5.03:0009 */

我不知道出了什么问题。如果我用较小的数字替换 other.vertexQty(399) 有什么有趣的。例如:

        this->weights = new NodeWeight[10];

不抛出异常。你能告诉我有什么问题吗?

【问题讨论】:

  • 能否在异常发生时包含other.vertexQty 的值?
  • 请在异常发生时包含sizeof NodeWeight
  • 你为什么首先使用内置数组和new?无论如何,尝试发布 MCVE。
  • int n, m; n = other.vertexQty; m = sizeof(新节点权重); //n = 399; m = 4

标签: c++ visual-studio-2013 heap-memory


【解决方案1】:

上线

   this->contents = new int[other.vertexQty]();

最后你有一个额外的“()”。 自函数:

   new[](size_t) 

需要一个字节大小并且您没有传递它,它要么抛出异常,要么分配未知大小的内存,因此以下创建适用于小数字。

我想删除它应该可以。

【讨论】:

  • 这无济于事,但感谢您指出这一点。可能你把我从更多奇怪的问题中解救了出来。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-10
  • 2019-01-09
  • 2017-02-19
  • 2014-06-01
  • 2014-06-28
  • 2018-04-02
相关资源
最近更新 更多