1

我正在使用一些在框架上运行的遗留类型代码,所以我无法真正解释在较低级别发生了什么,因为我不知道。

但是,我的代码创建了一系列目标。

int maxSize = 20;
    myObjects = new Object*[maxSize+1];

    myObjects[0] = new item1(this);
    myObjects[1] = new item2(this);

    for(int i=2; i != maxSize+1; i++){
          myObjects[i] = new item3(this);
        }

    myObjects[maxSize+1] = NULL;

如果maxSize大于 30,我会收到一大堆我从未见过的错误。Visual Studio 在 xutility 突出显示中出现错误:

const _Container_base12 *_Getcont() const
    {   // get owning container
    return (_Myproxy == 0 ? 0 : _Myproxy->_Mycont);
    }

我以前从未使用过 Malloc,但这就是问题所在。我应该分配使用它来避免这个问题吗?

4

4 回答 4

5

The absolute value of maxSize is probably not a culprit: allocating 30 pointers should go without trouble on any computer, including most micro-controllers. Using malloc is not going to change anything: you are doing your allocation the way you're supposed to do it in C++.

Here is the likely source of your error:

myObjects[maxSize+1] = NULL;

You have allocated storage for maxSize+1 items, so the valid indexes are between 0 and maxSize. Writing one past the last element is undefined behavior, meaning that a crash could happen. You got lucky with 20 elements, but 30 smoked out this bug for you. Using valgrind utility is a good way to catch memory errors that could cause crashes, even if they currently don't cause them.

int maxSize = 20;
myObjects = new Object*[maxSize+1];

myObjects[0] = new item1(this);
myObjects[1] = new item2(this);

// if maxsize is 1, this loop could be trouble
for(int i=2; i != maxSize; i++){
    myObjects[i] = new item3(this);
}

myObjects[maxSize] = NULL;
于 2012-04-24T13:26:31.083 回答
2

You're going past the bounds with:

myObjects[maxSize+1] = NULL;

In your example, you created an array with 21 items. That will run from 0..20 but you're trying to write to the 21st element here.

The problem is not with new / delete as far as I can see, and I can't see any reason for switching to malloc here.

于 2012-04-24T13:28:34.080 回答
0

You should not use malloc() in C++; you should use new.

There's one possible exception to this: if you have to allocate a block of memory which you intend to pass as an argument to a function which is going to eventually free it using free(). If you used new to allocate such a block the free() would likely cause heap corruption. But this is purely hypothetical -- I've never seen such an API!

于 2012-04-24T13:27:15.997 回答
0

我认为您无法访问偏移量“maxSize+1”。解决方案如下:

myObjects = new Object*[maxSize+2];
...
myObjects[maxSize+1] = NULL;
于 2012-04-24T13:32:33.893 回答