Thorn.Ryzome Thorn.Ryzome - 1 month ago 14
C++ Question

Program crashing when accessing a specific struct member

No matter what I do I can seem to access x even though it is implemented nearly the same as y. Im unsure If its some kind of memory access issue. The program breaks at the first access of x with no compile errors or warnings.
Calling step in the CPU works fine if x is not there. Any help is wonderful.

ESys.h

#pragma once

namespace ESYS
{
struct InterconnectI
{
int y;
std::vector<uint8_t>& Ip;
std::vector<uint8_t>& Ir;

InterconnectI(std::vector<uint8_t>& p, std::vector<uint8_t>& r);
~InterconnectI(){};
void hi(int n);

};

struct CPUI
{
int x;

CPUI();
~CPUI(){};
void step(InterconnectI* i);

};

struct SystemI
{
CPUI* CPU;
InterconnectI* Interconnect;

SystemI(std::vector<uint8_t>& p, std::vector<uint8_t>& r);
void Step();
};
}


ESys.cpp

#include "stdafx.h"
#include "ESys.h"

namespace ESYS
{

InterconnectI::InterconnectI(std::vector<uint8_t>& p, std::vector<uint8_t>& r) : Ip(p), Ir(r)
{
y = 0;
}

void InterconnectI::hi(int n)
{
std::cout << "Interconnect " << n << std::endl;
}

CPUI::CPUI()
{
x = 5;
}

void CPUI::step(InterconnectI* i)
{
std::cout << "Step CPU -> " x; //Accessing doesn't work...
i->hi(x); //Passing doesn't work...
}

SystemI::SystemI(std::vector<uint8_t>& p, std::vector<uint8_t>& r)
{
CPUI* CPU = new CPUI();
InterconnectI* Interconnect = new InterconnectI(p, r);
}

void SystemI::Step()
{
CPU->step(Interconnect);
}
}


Main.cpp

#include "stdafx.h"
#include "ESys.h"

std::vector<uint8_t> pDat;
std::vector<uint8_t> rDat;

int main(int argc, const char *argv[])
{

ESYS::SystemI ESystem(pDat, rDat);
ESystem.Interconnect->y = 11;

for (;;)
{
ESystem.Step();
}
return 0;

}

AVK AVK
Answer

The problem is here:

SystemI::SystemI(std::vector<uint8_t>& p, std::vector<uint8_t>& r)
{
    CPUI* CPU = new CPUI();
    InterconnectI* Interconnect = new InterconnectI(p, r);
}

The results of new are assigned to the local variables CPU and Interconnect. The data members SystemI::CPU and SystemI::Interconnect remain uninitialized.

Comments