Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a pointer to struct in C++ automatically allocates memory for its members. Am I wrong?

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

like image 666
Fernando Aires Castello Avatar asked Dec 04 '22 05:12

Fernando Aires Castello


1 Answers

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.

like image 75
Fred Foo Avatar answered Feb 18 '23 08:02

Fred Foo