what is malloc in C++

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ayesha shahid
    New Member
    • Oct 2011
    • 1

    what is malloc in C++

    please help me convert it in C++ language

    Code:
    r->next=(class polynomial *)malloc(sizeof(class polynomial));

    help me its urgent
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    malloc is a function that dynamically allocates memory for something.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      malloc in C++ is malloc.

      All the C++ new operator does is call the class constructor after doing a malloc to allocate memory.

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        And the corollary of weaknessforcats statement is that by just calling malloc as you have done the constructor for the class does not get called, the class is left unconstructed.

        Of course you could always call the placement new operator (also note that in your code use of the keyword class is not required). Placement new constructs a class without allocating the data for it, it assumes that the data has already been allocated and you have to provide a buffer of the right size to construct the class in.

        Code:
        void *buffer = malloc(sizeof(polynomial));
        r->next = new(buffer) polynomial;
        
        // Destruction - call destructor directly
        r->next->~polynomial();
        There is almost never any need to do this (I've done it once in 20 years)

        If you haven't already it's time to look up the new operator in your favourite C++ text book (or on the net).

        Comment

        Working...