c++ - 0xC0000005 : Access violation reading location 0x0000000000000008

标签 c++ exception

我正在尝试制作一个名称生成器,它使用从三个不同数组访问的预设音节。

#include "main.hpp"

Namegen::Namegen() {
}

const char *Namegen::getFirst() {
    const char *name;
    int rNum = rng->getInt(0, 5);
    const char *firstSyllable = start[rNum];
    rNum = rng->getInt(0, 5);
    const char *secondSyllable = mid[rNum];
    rNum = rng->getInt(0, 5);
    const char *lastSyllable = end[rNum];

    name = firstSyllable + *secondSyllable + *lastSyllable;

    return name;
}

每个数组中共有 6 个音节,所以我将最小值设置为 0,将最大值设置为 5。总共六个数字。然而,出于某种原因,它看起来像是在某处生成 8?我不完全确定异常在说什么,但希望其他人知道。这是一个异常(exception)(即使它已经在标题中):

0xC0000005: Access violation reading location 0x0000000000000008.

这是我的 Namegen.hpp 文件(通过 main.hpp 文件链接):

#pragma once

class Namegen {
public:
    const char *start[6] = { "Ba", "Ce", "Ti", "Mo", "Lu", "Dy" };
    const char *mid[6] = { "ma", "te", "di", "so", "ku", "ly" };
    const char *end[6] = { "ban", "can", "dan", "fan", "gan", "han" };

    Namegen();
    TCODRandom *rng;
    const char *getFirst();
};

为什么会抛出这个异常,我该如何解决?

我已经到了可以使用以下代码成功连接值的地步:

std::string Namegen::getName() {
    int r = rng->getInt(0, 2);
    std::string firstSyll = fSyll[r];
    r = rng->getInt(0, 2);
    std::string midSyll = mSyll[r];
    r = rng->getInt(0, 2);
    std::string lastSyll = lSyll[r];

    std::string name = std::string(firstSyll) + std::string(midSyll) + std::string(lastSyll);

    return name;
}

但是,它现在抛出这个异常:

Exception thrown at 0x00007FF978AD9E7A (ucrtbased.dll) in AotDK.exe: 0xC0000005: Access violation reading location 0x0000000000000000.

最佳答案

name = firstSyllable + *secondSyllable + *lastSyllable; 远不是串联。 (编译器会编译它,因为它认为您正在对 firstSyllable 进行一些指针运算。)行为实际上是未定义的,因为您分配的不是 nullptr 的东西。或对象的地址 name .

放弃所有char*东西,然后使用 std::string反而。那么+ 充当连接,因为它是字符串类中的重载运算符。

您的数据将采用以下形式

std::vector<std::string> start = { "Ba", "Ce", "Ti", "Mo", "Lu", "Dy" };

它展示了 C++ 标准库的强大功能。你需要 #include <string>#include <vector>引入该功能。

关于c++ - 0xC0000005 : Access violation reading location 0x0000000000000008,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50755011/

相关文章:

java - macOS "Big Sur"检测深色菜单栏/系统托盘

c++ - 重写对集合的访问以避免 "double"查找

c++ - 静态类成员在构造时抛出异常

java - 它是一种测试 JUnit 函数内部抛出的异常的方法吗?

java - 您如何断言在 JUnit 测试中抛出了某个异常?

c++ - 检查数组中消息的最有效方法

c++ - 在集合中找到一对 C++

C++模板函数重载规则

python - 在 python 中对请求执行异常时出错

python - 如何在 Python 中打印异常对象的堆栈跟踪?