Does the following code invoke undefined behaviour? As far as I know we should always use new to create user defined objects dynamically because new in addition to malloc calls the constructor too.
#include <cstdio>
#include <cstdlib>
struct om
{
int a;
void fun()
{
a=10;b=10;
}
private : int b;
} s1; // structure(om) variable...
typedef struct om node;
int main()
{
node *s2=(node *)malloc(sizeof(node));
s1.fun();
printf("%d",s2->a);
return 0;
}
The above code prints 0. That means s2->a is automatically initialized to 0?
So I want to know is the behaviour of the program Implmentation defined, Undefined or Well defined?
mallocisn’t guaranteed to initialize the memory it allocates – if you want the memory to be filled with 0’s then usecalloc.