4

I wrote the following piece of code and I believed it would crash if I tried to access the members of a struct for which I didn't even allocate memory. But I was quite suprised that C++ automatically allocated memory for the struct. Is that normal behavior? For comparison, if you declare a pointer to an object and then try to access any members without actually creating the object with the operator "new", the program would crash. I'm just curious about why it works when I believe it shouldn't.

This is my program:

#include <stdio.h>

struct Produto
{
    int codigo;
    float preco;
};

int main()
{
    struct Produto* sabonete;
    sabonete->codigo = 654321;
    sabonete->preco = 0.85;

    printf( "Codigo = %i\n", sabonete->codigo );
    printf( "Preco = R$ %.2f\n", sabonete->preco );

    return 0;
}

OS: Windows 7
Compiler: MinGW GCC 4.6.1

4
  • 2
    You're wrong. This just appears to work - it's undefined behaviour.
    – jrok
    Feb 23, 2012 at 21:53
  • 6
    Fix the bugs in your code and the mystery will go away. Broken code does strange things, that's the way it is. Feb 23, 2012 at 21:56
  • The key problem with what you said is, "C++ automatically allocated memory for the struct". No it did not. A pointer is just a mem address, it doesn't know where it points.
    – Avi
    Feb 23, 2012 at 21:58
  • C++ does not automatically allocate memory. Run it under a heap checker and you'll get the reports of invalid memory references. C++ (like C) just doesn't check these by default, for performance reasons: this is bare-metal programming in a highlevel language.
    – sehe
    Feb 23, 2012 at 22:03

5 Answers 5

11

C++ did not automatically allocate memory; the pointer holds an arbitrary value which just happened to be a valid address in your program's memory space so you didn't get a segfault. Your program exhibits undefined behavior and it might not work the next time you run it.

Undefined behavior does not guarantee a crash, that's why it's called undefined.

6
  • But when printf executes it prints the exact values that I assigned to the members of the structure, so in fact it works. Feb 23, 2012 at 21:54
  • 9
    @FernandoAiresCastello: No, in fact it does not. You are invoking undefined behavior. By definition anything can happen. Your code is incorrect. Feb 23, 2012 at 21:55
  • 1
    It works until . . . You put the data in, and then do some more work, and it changes out from under you. If you write programs like this you'll find that they have seemingly random behavior and also security bugs.
    – Kyle Butt
    Feb 23, 2012 at 22:00
  • 2
    It works in the same way barrelling down the freeway at 80 miles per hour with three feet between your front bumper and the next car's "works". You may be able to get away with it, but chances are the slightest thing will go wrong and then you've royally crashed.
    – Kaganar
    Feb 23, 2012 at 22:00
  • 1
    FTR 80 miles per hour is about 130 kilometers per hour. Feb 23, 2012 at 22:26
4

You've run into Undefined Behavior

on line 2 it's undefined what sabonete points at. It could point at memory that won't break anything if you change it, or it could point at memory that launches the nukes when you change it.

C++ isn't allocating you memory at all, you're just stomping on memory that happens not to break anything.

2

Nope, exactly the opposite. That pointer is uninitialized and you are invoking UB by dereferencing it. If you want a pointer you have to initialize it, either via an existing pointer or by calling new (or, better yet as this is C++, some object which works as a container to handle the allocation/destruction, i.e., RAII).

By definition, undefined behavior means that anything may happen. Sure, it may appear to work at times due to memory layout, whatever, but there is no guarantee that it always will and you should never write code like this.

3
  • What strikes me is that, if the pointer holds an arbitrary memory address, then why everytime I run this code this arbitrary memory address points exactly at the structure. Feb 23, 2012 at 21:59
  • 1
    @FernandoAiresCastello: You still seem to be confused. There is no rhyme or reason when you invoke undefined behavior. the behavior is undefined. Anything may happen, no need to reason as to why it does. Add a variable declaration above that pointer and you may see a crash. Maybe not though. Again, undefined behavior. Feb 23, 2012 at 22:01
  • Ok, thanks. I thought it actually worked because the values were correctly assigned to the members of the struct. But I don't usually do this, I always initialize pointers. I was just experimenting to see what would happen :) Feb 23, 2012 at 22:07
0

As the g++ compiler does not initialize an unallocated pointer to NULL, it may be that it points to some part in the memory that contains data that seems at the first look right.

To answer the question, yes it is the normal yet undefined behaviour when you are not willing to allocate memory for your objects :)

0
0

If you are interested in what "could have been happened" under the hood, consider that sabonete on your platform is 4 bytes wide (as a pointer) and since your main didn't declare the parameters (that the OS let in any case aailable), may be occupy the same memory space, that is typically in parameter reverse order.

It that's true, it overwrites the char** argv that points to a pointer array (it should contain a minimum of 16 of them) that points to the strings that contains the command line parts.

You're actually assigning your values writing them over that array, and since it belongs to your program, the OS doesn't complain. And since you never refer it's original values and nobody else changes them, everything looks working fine.

But it's not becuse it IS fine. It is because you had been lucky in fitting a space in use for something else you are not -in this case- interested in.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.