You are interpreting a piece of raw memory (which is what std::malloc()
returns) as an object (the cast (node*)malloc(...)
) and then accessing a member on it (s2->a
). In practice you might get away with it as long as the type only contains members of built-in types and no pointers, but technically that's invoking undefined behavior.
Invoking undefined behavior is bad, because it allows your program to do anything. It might crash your program, silently produce wrong results, format your HD, burn your CPU, make your pregnant, or it might work the way you expected it to. It might behave one way now, but differently with a new compiler version, an OS upgrade, on another platform, at a customer's site, when your boss watches, on Sundays, or depending on the moon phase.
A constructor is what turns raw memory into a valid object. Constructors are run automatically when you create objects on the stack, global objects, or using a new
expression. You can separate memory allocation and construction by using placement new. Doing so, you could take memory allocated by std::malloc()
and invoke a constructor on it. But why would you want to do this? Except for optimizations (and as a mechanism used by types in the C++ std lib), placement new is rarely ever needed.
Why was your question tagged C++
anyway? Of course, a C++ compiler would compile it with a few obvious fixes, but except for the C++-style includes of C std lib headers, there's nothing C++ about it, and it's full of C-isms.
Are you sure you want to program C++? Or aren't you more comfortable with C? If so, it might be better to stick with C than writing C in C++. Much of what's considered good in C is considered bad in C++.