Carlos
Carlos

Reputation: 125

Visual Studio: Variable is being used without being initialized

While using Visual Studio I get a run-time check failure due to a variable being used without being initialized. Something like this is going on:

SomeStruct ss;
SomeOtherStruct sos = {ss};

Later on in the code I initialize sos.ss before I actually use it.

I appreciate that Visual Studio catches it but this should be a warning since I don't really use it, I just pass it around and not throw a run-time exception while I'm running the program.

I am using C not C++ but haven't found a way to tell VS to use C (I need to manually put .c files and uncheck use pre-compiled headers). Anyway, how can I tell VS to stop complaining about this exception. Unmarkins "break when this exception type is thrown" does not usually work (problem tends to come back).

Upvotes: 0

Views: 1030

Answers (2)

Paul Ogilvie
Paul Ogilvie

Reputation: 25276

Your basic error is that you seem to think that SomeOtherStruct sos = {ss}; will establish a pointer or "alias" of ss with sos so that when, at some later point in your code, you initialize ss, you also intitialize sos.

But that is not the case in C. You simply copy al the values of ss to sos and since ss is uninitialized, you copy garbage to sos. And that garbage temains there even when you initialize ss later on.

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234655

The behaviour of SomeOtherStruct sos = {ss}; is undefined if ss contains uninitialised plain old data which are not char, unsigned char, or signed char types.

This is because you are reading uninitialised data in the initialisation of sos.

Visual Studio therefore is being very helpful.

In C, you can write SomeStruct ss = {0}; which will fix this. In C++ you can drop the 0. But why do you see the need to initialise sos from an uninitialised ss?

Upvotes: 4

Related Questions