If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register or Login
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Re: malloc for union inside structure fails.

VS2010 compiles the posted code (except that main() must return a value).

Your code is so C-ish. Why not graduate to C++? Rather than a union of pointers you could use inheritance (two (or more) structs/classes derived from a common base struct/class). And you could use new/delete for allocations.

Re: malloc for union inside structure fails.

Originally Posted by shreyaswaghmare

Hi Guru's,
I have some problem while allocating memory to a union inside structure.

If your problem is a compilation issue, it would help if you posted the name and version of the compiler you're using. The issue as you've described is not a run-time issue with malloc(), it is an issue with source code management.

Secondly, if it is the same compiler, then obviously your code is different on the two systems. A compiler just doesn't give out errors because it is run on another computer -- the code must be different in some way on the machines, or the compilers are different (different compiler brand and/or version).

Re: malloc for union inside structure fails.

I would throw away the compiler you are using for system2!! You don't say what compilers you are using but your code works fine for me using Visual Studio 2003 onwards. Note that if the call to calloc fails, then your program doesn't terminate as it probably should but just outputs an error to stderr and trys to continue with all sorts of bad memory problems!!! Also if the malloc call for MYSTRUCT2 fails then you are not freeing the memory already allocated for MYSTRUCT1. Personally when I use pointers I nearly always typedef a pointer definition so that I don't have a load of * cluttering up my code. As below