Results 1 to 3 of 3

Thread: new vs malloc Q: [RESOLVED]

  1. #1

    Thread Starter
    PowerPoster Halsafar's Avatar
    Join Date
    Jun 2004
    Location
    Saskatoon, SK
    Posts
    2,339

    new vs malloc Q: [RESOLVED]

    It seems that while writing a template dynamic array class..I attemp to use malloc to initialize the array and when I free it I always get a block error.

    It is as simple as:

    //BLOCK ERROR
    T *m_Pool;
    m_Pool = (T*)malloc(uiSize);
    free(m_Pool);


    //WORKS FINE
    T* m_Pool;
    m_Pool = new T[uiSize];
    delete [] m_Pool;




    Edit: I am not multiplying the uiSize by the size in bytes -- malloc needs that. My fault.
    "From what was there, and was meant to be, but not of that was faded away." - - Steve Damm

    "The polar opposite of nothingness is existance. When existance calls apon nothingness it shall return to nothingness." - - Steve Damm

    "When you do things right, people won't be sure if you did anything at all." - - God from Futurama

  2. #2
    Fanatic Member
    Join Date
    Dec 2003
    Posts
    703

    Re: new vs malloc Q: [RESOLVED]

    Template class + malloc = bad..

    If your templated type has a constructor, malloc won't call it, so your objects don't get constructed properly. Use new in C++, malloc in C.
    an ending

  3. #3
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594

    Re: new vs malloc Q: [RESOLVED]

    malloc(uiSize);
    allocates uiSize bytes. Does nothing else.

    new T[uiSize]
    allocates sizeof(T)*uiSize bytes. Calls the default constructor on each object.
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width