0xC0000005: Access violation reading location 0x0000000000000008

2

I'm trying to make a name generator that uses preset syllables accessed from three different arrays.

#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;
}

There are a total of 6 syllables in each array, so I have the min set to 0, and the max to 5. Six numbers in total. Yet, for some reason, it looks like it's generating an 8 somewhere? I'm not entirely sure what the exception is talking about, but hopefully someone else does. This is the exception (even though it's in the title already):

0xC0000005: Access violation reading location 0x0000000000000008.

This is my Namegen.hpp file (linked through the main.hpp file):

#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();
};

Why is it throwing this exception, and how do I fix it?

I got it to the point that I can successfully concatenate the values, using the following code:

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;
}

However, it now throws this exception:

Exception thrown at 0x00007FF978AD9E7A (ucrtbased.dll) in AotDK.exe: 0xC0000005: Access violation reading location 0x0000000000000000.
c++
exception
asked on Stack Overflow Jun 8, 2018 by Jacob McNamara • edited Jun 8, 2018 by Jacob McNamara

1 Answer

6

name = firstSyllable + *secondSyllable + *lastSyllable; is nowhere near a concatenation. (The compiler compiles it as it thinks you're doing some pointer arithmetic on firstSyllable.) The behaviour is actually undefined as you are assigning something that isn't nullptr or the address of an object to name.

Ditch all the char* stuff, and use std::string instead. Then + will act as a concatenation as it's an overloaded operator in the string class.

Your data would then take the form

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

which demonstrates the power of the C++ standard library. You need to #include <string> and #include <vector> to bring in that functionality.

answered on Stack Overflow Jun 8, 2018 by Bathsheba • edited Jun 8, 2018 by Bathsheba

User contributions licensed under CC BY-SA 3.0