Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

mapping between union and malloc memory

malloc

  • Please log in to reply
3 replies to this topic

#1 dhiru

dhiru

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 27 November 2008 - 09:45 AM

(i m a student
our placements are going on
last week HP visited our campus
in the technical round they asked me this question)


union a{
some data;
};

mem=malloc(80);
and there is some data copied to the mem variable
now how one can map the mem to a
  • 0

#2 solartic

solartic

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 94 posts

Posted 27 November 2008 - 11:52 AM

something like this should work i guess:
union a *new = NULL;

mem=malloc(80);

if(mem != NULL)
{
     new = (union a*)(&mem);
}

  • 0

#3 dargueta

dargueta

    I chown trolls.

  • Moderator
  • 4854 posts
  • Programming Language:C, Java, C++, PHP, Python, JavaScript, Perl, Assembly, Bash, Others
  • Learning:Objective-C

Posted 27 November 2008 - 10:06 PM

That's not correct, since mem would have to be a pointer. That would assign the data beginning with mem somewhere in memory to the pointer. And you can't use new as a variable in C++, so I wouldn't use that either.

typedef union {
    /*some stuff*/
}A;

void *mem = malloc(/*arbitrary size*/);
A *myunion = (A *)mem;

  • 0

#4 solartic

solartic

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 94 posts

Posted 27 November 2008 - 11:30 PM

ahh yeah indeed mem would have to be a pointer
well about the new i assumed c but yeah its better to avoid it
  • 0





Also tagged with one or more of these keywords: malloc

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download