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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With