我已经研究了这个问题,但是我并没有得到很好的答复,所以我想在这里问。

我正在使用C++进行项目,其中涉及一些内存操作(分配动态char数组,并使用new放置将内存地址和完整对象放入这些数组中)。

每次在Visual Studio中调试程序时,我都会遇到一个非常令人沮丧的问题:通常会弹出一条消息,提示“ProjectName.exe触发了断点”。有时会说类似“在2-Kennel.exe中,在0x0FFD66CB(ucrtbased.dll)处引发异常”:Kennel.exe:0xC0000005:访问冲突读取位置0xFFFFFFF5。

这是相关类的代码

类别

#ifndef CAT_H
#define CAT_H

#include <string>
#include "Kennel.h"

using std::string;

class Cat {
private:
    static Kennel catKennel;
    int _id;
    string _name;

    Cat(int i, const string& nm) : _name(nm) { // Note initializer list
        _id = i;
    }

    void* operator new(size_t size){
        return catKennel.allocate();
    }
public:
    static Cat* create(int id, const string& name) { // Factory method
        return new Cat(id, name);
    }

    void operator delete(void* loc) {
        catKennel.deallocate(loc);
    }
};

Kennel Cat::catKennel(sizeof(Cat), 5);

#endif

狗窝
#ifndef KENNEL_H
#define KENNEL_H

#include <cstddef>
#include <cassert>
#include <iostream>
#include <new>

class Kennel {
private:
    static const size_t _BUCKET_COUNT = 10;
    const size_t _BUCKET_SIZE;
    const size_t _ELEM_SIZE;
    char* buckets[_BUCKET_COUNT];
    //char** buckets;
    char* availableBlock;
public:
    Kennel(size_t elemSize, size_t bucketSize = 5);
    ~Kennel();
    void* allocate(); // Get a pointer inside a pre-allocated block for a new object
    void deallocate(void*); // Free an object's slot (push the address on the "free list")
};

#endif

狗窝
#include "Kennel.h"

Kennel::Kennel(size_t elemSize, size_t bucketSize) : _ELEM_SIZE(elemSize), _BUCKET_SIZE(bucketSize) {
    //Set each element in buckets to nullptr.
    for (int i = 0; i < _BUCKET_COUNT; i++)
        buckets[i] = nullptr;
}

Kennel::~Kennel() {
    //Delete each character array in buckets.
    for (int i = 0; i < _BUCKET_COUNT; i++) {
        if (buckets[i] != nullptr)
            delete[] buckets[i];
    }
}

void* Kennel::allocate() {
    //If there is no available bucket: create a new one.
    if (availableBlock == nullptr) {
        //Find next array index in buckets array where we can create a new bucket.
        int nextNullBucketIndex = -1;
        for (int i = 0; i < _BUCKET_COUNT; i++) {
            if (buckets[i] == nullptr) {
                nextNullBucketIndex = i;
                break;
            }
        }
        assert(nextNullBucketIndex > -1); //If there is no space to create another bucket: exit.

        //Create a new bucket.
        buckets[nextNullBucketIndex] = new char(_BUCKET_SIZE * _ELEM_SIZE);
        availableBlock = buckets[nextNullBucketIndex];
        char* tempBlock = availableBlock;

        //Put the address of the next block inside each block.
        std::cout << "Bucket " << nextNullBucketIndex << ": ";
        for (int i = 0; i < _BUCKET_SIZE - 1; i++) {
            std::cout << static_cast<void*>(tempBlock) << ' ';
            new (tempBlock) char*(tempBlock += _ELEM_SIZE);
        }
        std::cout << static_cast<void*>(tempBlock) << std::endl;
        new (tempBlock) char*(nullptr); //The last block doesn't get an address, put nullptr in it.
    }

    char* tempAvailable = availableBlock;
    availableBlock = *reinterpret_cast<char**>(availableBlock);

    std::cout << "Returning: " << static_cast<void*>(tempAvailable) << std::endl;
    return static_cast<void*>(tempAvailable);
}

void Kennel::deallocate(void* loc) {
    new (loc) char*(availableBlock); //Store availableBlock's contained address in loc.
    availableBlock = static_cast<char*>(loc); //Set availableBlock's contained address to be loc's address.
}

每次我运行程序时,问题都会有所不同。这是一些有关我尝试运行它时遇到的常见问题的信息。

在分配中尝试执行Kennel.cpp第48行时,它通常会中断
std::cout << "Returning: " << static_cast<void*>(tempAvailable) << std::endl;

它经常在删除Cat对象的主要函数中折断。

在调用Kennel的解构函数时,有时会在程序结束时中断。

等等...

就像我说过的那样,决定中断哪一行代码似乎是随机的。另外,我几乎可以确定问题出在Kennel类上,因为我通过 friend 的Kennel.h和Kennel.cpp使用了我的代码,并且可以正常工作。

任何帮助将不胜感激。

最佳答案

buckets[nextNullBucketIndex] = new char(_BUCKET_SIZE * _ELEM_SIZE);

这仅分配一个char,而不分配它们的数组。然后,您可以将自己不拥有的内容写入内存。 std::stringnew相同的内存,然后您的堆就被搞砸了。

09-25 19:16