I have been playing around with pointers and made a little mistake of this type:

class D{
             int a;

int main()

    D *x;        //As you can see I didn't allocate memory at all...
    x->a=3;      // ... but initialized a member variable 

    return EXIT_SUCCESS;

I get run-time error if compiled in DEVC++.

But I tried the same in Code::Blocks, and it works, as if I regularly allocated memory before initializing... hm... what?

Can anyone explain me this behaviour, I know some rules differ from compiler to compiler, but what's the matter with this one?


From what I can see, any compiler should compile the code, but most should issue a warning about the pointer being uninitialised.

As far as I understand things:
With most compilers, when you declare a pointer and you don't initialise it to point to anything; it will point to an arbitrary memory address. So the pointer could be pointing to anywhere in memory. Then when you assign a value to an address pointed to by the pointer as you have, I'm not sure if that's undefined behaviour or what. (Never really looked that hard at the standard docs!). But in the cases where it actually 'works' (e.g. using g++ or Codeblocks with mingw etc); for example: When you assign the value of 3 to x->a in your code. You're most likely writing over the contents of the arbitrary memory address/addresses pointed to by the pointer. Which is probably more than a little dodgy.

If you initialised the pointer to null where you're declaring it in your code, the code would compile on C::B without warning, but you'd get a seg-fault at runtime (exactly as you're reporting with DevC++). So perhaps DevC++ is automatically setting uninitialised pointers to unll. IDK, but that's one possible explanation for the behaviour you're seeing.

Either way, regardless of the compiler you're using. When declaring pointers you should always either:
A. Assign them to point to null (or 0) if you aren't going to be using them right away.
B. Assign them to point to an existing object or a new object of the relevant type.

Also you should always ensure that pointers are valid before attempting to dereference them or assign values to them, unless you are absolutely 100% certain that they will always point to something valid!

Disclaimer: I could be wrong on some of the finer technical, compiler related details. But if that is the case, someone will correct me! Heh heh! XD

This article has been dead for over six months. Start a new discussion instead.