c++ - #define 导致 "Access violation reading location"

标签 c++

我认为这是 child 问题,但我找不到如何解决它的信息。

//*.h:

class Foo
{
    #if defined(RedefChallangesCount)
        static const mainDataType ChallangesCount = 500;
        #undef RedefChallangesCount
    #else
        static const mainDataType ChallangesCount = 1;
    #endif

    ...
    int _correctAnswers[ChallangesCount];

    ....
}

在我的 VS 测试类中:

#include "stdafx.h"
#include "CppUnitTest.h"
#define RedefChallangesCount
#include "..\Core\ChallengeManager.h"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace Brans;

namespace CoreTests
{
    TEST_CLASS(SomeTestClass)
    {
    public:
        TEST_METHOD(SomeTestMethod)
        {
            Foo* cm = new Foo();
            cm->Method();
            ...
            delete cm;
        }
    }
}

在我看来,我所做的一切都像在文档中一样,但是当使用#define RedefChallangesCount 行运行测试时,我遇到了奇怪的错误,例如“访问违规读取位置”,有时是错误的数组 _正确答案。同时我看到 ChallangesCount 是预期的 500。如果我评论 #define RedefChallangesCount 行 - 所有错误都消失了...... 有什么问题吗?

最佳答案

你的 #undef 让我怀疑这个 header 被包含在其他地方(例如 ChallengeManager.cpp,这意味着你最终会得到你的 _correctAnswers 在某些地方的大小为 500 而在其他地方的大小为 1,这肯定可以解释您的崩溃。

(编辑):您的测试是解决方案中的一个单独项目,主要代码在其自己的项目中,还是您的代码全部直接编译在测试项目中?

为了安全起见,在 VS 构建配置中设置您的 #define(对于链接到测试中的所有项目 - 您需要为此添加一个测试构建配置,并改为使用它测试版本的调试/发布)而不是在代码中定义它,并删除 #undef

关于c++ - #define 导致 "Access violation reading location",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19786329/

相关文章:

c++ - 重载==函数没有被调用

c++ - 将 STL 容器用于 boost::interprocess::managed_shared_memory

c++ - Microsoft Cryptographic API 是否允许从字节流创建 ECDSA key ?

c++ - 通过 fread 将 jpg/png 读入点数组

c++ - 记忆化递归 C++

c++ - Opencv 使用 cv::Mat 创建新图像

c++ - 为什么按照 ISO C++ 避免在 new 之后检查 null

c++ - 在访问工作线程的 lambda 中捕获的 vector 列表中的元素的引用时,是否需要互斥锁?

c++ - Lint:调用函数 'memcpy(void *, const void *, std::size_t)' 违反语义 '(3n>4)'

c++ - 字符串中奇数位和偶数位的数字之和