# Unity C++ Runtime Error With Odd Workaround

This topic is 1252 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I'm experiencing a runtime error in Visual C++ 2010. I can work around it, but I don't understand the error and I don't understand why the workaround works. I'm going to try and strip this down to as basic of an example as possible.

class Object
{

int data[10];

};

class A : public Object

{

void Init();

};

A::Init()

{

data[0] = 24;

}

class B : public Object

{

void Init();

};

B::Init()

{

data[0] = 48;

}

Object * gpObj;

A a;

B b;

void main()

{

a.Init(); // <--this line creates an access error, unless...

b.Init();

gpObj = &a; // <--if I put this line first, a.Init() and b.Init() work as intended

}

It's very confusing for me why I need to reorder the code in this way to get it to work. I could understand if gpObj were being used to access the variable, obviously, but it's not. The only thing I'm changing is the order of the instructions. Any insight the community may have is welcome.

##### Share on other sites

Unable to reproduce.

What is the exact code that produces the error?

Edited by fastcall22

##### Share on other sites

Your basic example is incomplete. Most likely you are using the global gpObj variable in one of the Init functions, and the Init functions are called before you assign a valid pointer to gpObj...

##### Share on other sites
I'm confused how this is even compiling, due to this:

class Object
{
int data[10];
};

Class members are _private_ by default. That means that derived classes will not be able to access these members. You will need to declare the data member in a protected or public access level for A to have access to it.

--

The runtime error makes no sense. This probably isn't the actual code you're testing. Are these class definitions in separate files, by chance, and is your actual test function not main? Global variable initialization orders could explain this, though they would all be initialized before main is executed.

##### Share on other sites

Unable to reproduce.

What is the exact code that produces the error?

I've tried my best to maintain the essence of what the code is doing in my example. I know you're thinking, the answer must be in something he's doing in the REAL code that's not represented in this example. But it's really not. I'm not uploading the exact code because it's just too big. I realize that's not helpful. Try to focus on the fact that moving the green line ahead of the red line fixes the problem. Because that part of the example is exactly the same as the source, minus some name changing.

Your basic example is incomplete. Most likely you are using the global gpObj variable in one of the Init functions, and the Init functions are called before you assign a valid pointer to gpObj...

Nothing even sort of close to that is happening. But specifically, I can assure you, the global pointer is not referenced in any way in a.Init() or by anything it calls (it actually doesn't call anything). It really is as benign as assigning a literal value to member data.

I'm confused how this is even compiling, due to this:

class Object
{
int data[10];
};

Class members are _private_ by default. That means that derived classes will not be able to access these members. You will need to declare the data member in a protected or public access level for A to have access to it.

--

The runtime error makes no sense. This probably isn't the actual code you're testing. Are these class definitions in separate files, by chance, and is your actual test function not main? Global variable initialization orders could explain this, though they would all be initialized before main is executed.

To answer the first part, I'm using structs, not classes, so that's a flaw in the example. It does indeed compile, and in the given scenario, works as expected.

The structs Object, A, and B, are each defined in seperate files. The instances in question, gpObj, a, and b, are declared globally as extern, and then created globally in the cpp file that references them. The function that references them is not main, but as you say, they are all initialized by the time this code is executed.

And regardless to all other concerns, putting the green line in front of the red line fixes the problem, where there is positively no reference to the global pointer as a result of the call to a.init().

Thanks to all for considering this issue and for your feedback. Just to reiterate, no code will be posted. Feel free to conclude that you have insufficient information to understand the problem.

I don't think the answer is even in the code, at least not in any straightforward way. I think my problem is in my lack of understanding of how, where, and why memory is allocated to a large number of bulky, complex global variables. I think somewhere somehow something is getting created over top of something else, in a way that's beyond my ability to anticipate. But that's just my guess.

##### Share on other sites

The problem and "solution" you describe is pretty much a symptom of either accessing uninitialized memory or writing out of bounds.

Not much more can be said without seeing the real code. The problem is simply not in that sample code you posted.

##### Share on other sites

Endurion, as an aside, it's funny that you quoted the word "solution", as you were the only one to use it. It's not important, just an interesting non sequitor.

Anyway, dear everyone, I take back everything I said. There was a reference to gpObj in a.init() (about 6 calls deep) that I didn't catch before. I sort of blame VC++ for reporting the wrong line # at which the access error occurs. But the bottom line is that I'm a stupid idiot and wasted everyone's time. The problem was in the code and it wasn't even that complicated. Oh well. At least my universe makes a little more sense now. And I'm slightly less paranoid about ninja heap errors. Just a little.

For what it's worth, your collective feedback did help me come to the realization.

Edited by bryanismagic

##### Share on other sites

I quoted the word "solution" since if the problem was writing out of bounds, it would not actually solve the problem. It would merely hide the symptom until it reappears somewhere else.

Anyhow, you found the actual problem and fixed it. That's what we're here for.

##### Share on other sites

Most likely you are using the global gpObj variable in one of the Init functions, and the Init functions are called before you assign a valid pointer to gpObj...

There was a reference to gpObj in a.init() (about 6 calls deep) that I didn't catch before.

Never doubt the <awesome> power of guesswork!

Edited by tonemgub

##### Share on other sites

I'd recommend in future making it very clear if your example program actually demonstrates the behaviour or if it is just intended to be a simplification. I'd also recommend actually trying to make your example program exhibit the behaviour: the process of reducing the problem to the minimum conditions that reproduce it can be a very effective way of solving the problem.

I sort of blame VC++ for reporting the wrong line # at which the access error occurs

This is surprising. It is unclear to me how experienced you are, but regardless, are you sure you weren't a simple mistake like trying to debug a release build? I've heard of the debug database getting corrupt or out of date in older versions, maybe a clean build would have helped.

It might be worthwhile re-introducing such a bug and trying to get VC++ to give you the correct information, as you'll almost certainly need to investigate similar issues in future.

##### Share on other sites

hi,

i must say first of all build a debug version of your application, then debug it

if an error occurs, you can fined it easyly

##### Share on other sites

Something to be wary of, and i've seen it happen to my code, if the compiler is doing any form of optimization, functions, classes, and variables may not be executed in the order that you expect... quite aside from a declaration being made in another piece of code.

When the error occurs (say an out of bound or buffer overrun) it may not breakpoint properly and can give wrong line numbers in extreme cases.

• 10
• 11
• 9
• 11
• 9
• ### Similar Content

• So I am building a turn based rogue-like (think CDDA). The game is going to have a very large map (up to 1000's x 1000's) however to alleviate most of that I obviously can't render everything so there will just be render a certain radius around the player and just load in and out data as the player moves.
The next major system I am prototyping is making interactive tiles destructible and pretty much everything will be destructible besides basic landscape (cars, doors, windows, structures, etc. will be destructible)
While I am only rendering a certain amount of tiles around the player, I want to keep the amount of colliders active at one time to be as small as possible for performance and currently the tilemap tool I use automatically merges colliders together.
So instead of creating a separate colliders for each of these tiles and having the destructible behavior tied to that object (which my tilemap tool would allow me to do) I was thinking that I would store an array of all the X and Y locations for the interactive tilemap layer and let the tilemap manage the colliders.
Then when I hit a collider on the interactive tilemap layer, instead of of getting the behavior for how to deal with the destruction for that tile from that game object, I would pull it from the array I mentioned earlier based on the tile I attempt to interact with which I already have.
Does this sound like a good approach? Any other recommendations would be welcomed.

• Hey guys,
I have a really weird problem. I'm trying to get some data from a REST service. I'm using the following code:

private void GetTheScores() { UnityWebRequest GetCommand = UnityWebRequest.Get(url); UnityWebRequestAsyncOperation operation = GetCommand.SendWebRequest(); if (!operation.webRequest.isNetworkError) { ResultsContainer rez = JsonUtility.FromJson<ResultsContainer>(operation.webRequest.downloadHandler.text); Debug.Log("Text: " + operation.webRequest.downloadHandler.text); } } The problem is that when I'm in Unity's editor, the request doesn't return anything (operation.webRequest.downloadHandler.text is empty, the Debug.Log command just prints "Text: "), but when I enter the debug mode and insert a breakpoint on that line, then it returns the text properly. Does anyone have an idea why is this happening?
The real problem I'm trying to solve is that when I receive the text, I can't get the data from the JSON. The markup is really simple:
[{"id":1,"name":"Player1"},{"id":2,"name":"Player2"}] and I have an object that should accept that data:
[System.Serializable] public class ResultScript { public int id; public string name; } There is also a class that should accept the array of these objects (which the JSON is returning):
[System.Serializable] public class ResultsContainer { public ResultScript[] results; } But when I run the code (in the debug mode, to get any result) I get an error: ArgumentException: JSON must represent an object type. I've googled it but none of the proposed solutions work for me.
Also (regardless if I'm in the debug mode or not) when I try to do some string operations like removing or adding characters to the GET result, the functions return an empty string as a result
Can you help me with any of these problems?
Thank you
• By nihitori
The Emotional Music Vol. I pack focuses on beautiful and esoteric orchestral music, capable of creating truly emotive and intimate moods. It features detailed chamber strings, cello and piano as the main instruments, resulting in a subtle and elegant sound never before heard in video game royalty-free music assets.

The pack includes 5 original tracks, as well as a total of 47 loops based on these tracks (long loops for simple use and short loops for custom / complex music layering).

Unity Asset Store link: https://www.assetstore.unity3d.com/en/#!/content/107032
Unreal Engine Marketplace link: https://www.unrealengine.com/marketplace/emotional-music-vol-i

A 15 seconds preview of each main track is available on Soundcloud:

• Another one of our new UI for #screenshotsaturday. This is the inventory screen for showing what animal fossils you have collected so far. #gamedev #indiedev #sama

• We're looking for programmers for our project.
Our project is being made in Unity
Requirements:
-Skills in Unity
-C#
-Javascript
-Node.js
We're looking for programmers who can perform a variety of functions on our project.
Project is a top-down hack-and-slash pvp dungeon-crawler like game. Game is entirely multiplayer based, using randomized dungeons, and a unique combat system with emphasis on gameplay.
We have a GDD to work off of, and a Lead Programmer you would work under.
Assignments may include:
-Creating new scripts of varying degrees specific to the project (mostly server-side, but sometimes client-side)
-Assembling already created monsters/characters with existing or non-existing code.
-Creating VFX
-Assembling already created environment models
This project is unpaid, but with royalties.

---