Thread: dynamic allocation question

  1. #1
    Registered User
    Join Date
    Aug 2001
    Posts
    11

    Post dynamic allocation question

    I've got some questions about dynamically allocating an array. I've got the allocation to work, but I was wondering why the following works:

    (this constructor has been edited so it only shows the allocation stuff)

    stack::stack( char name, int size )
    {


    stck = (char *)malloc( size * sizeof(char));
    *stck = '\0';


    }

    1. Why is the (char *) cast required in C++? When I was learning C, I once saw a post from Stee saying that the cast is optional and bad because it can mask an error (something I found to be true). If you take the cast out, the above line won't compile in C++ (but it will in C).

    2. Why does the cast create an array of char's (1 byte each on my computer) instead of an array of pointers (4 bytes each).

    3. In my destructor, I have:

    free( stck )

    Why does this work? Seems to me this should only free the first member of the array, while leaving the others in memory. If that's unclear, I think of it as akin to freeing the head of a linked list and assuming that destroys the entire list.


    Thanks in advance for your help!

  2. #2
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    1) As there is a greater emphasis on type safety in C++ you can't assign void pointers to any other pointer without first casting it. If you use 'new' insteat of 'malloc' you don't have to typecast the returning pointer(unless it is a different type).

    2) As malloc returns a void pointer, casting it to a char pointer is not changing what it points to. It just tells the compiler how you are going to use this pointer.

    3) I think the details depend on the implementation of malloc, but a call to malloc also creates some space for bookkeeping info that is used by free to release the memory.

    If you are using dynamic memory in c++ (especially involving classes) you should get used to using the new and delete operators instead of malloc and free.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dynamic allocation (I thought it would crash)
    By Baaaah! in forum C Programming
    Replies: 16
    Last Post: 11-30-2005, 05:10 PM
  2. Dynamic allocation
    By SARAHCPS in forum C Programming
    Replies: 5
    Last Post: 11-13-2005, 02:24 PM
  3. Dynamic memory allocation
    By amdeffen in forum C++ Programming
    Replies: 21
    Last Post: 04-29-2004, 08:09 PM
  4. Replies: 7
    Last Post: 05-06-2002, 11:40 AM
  5. Dynamic Memory Allocation for fstream (binary)
    By kuphryn in forum C++ Programming
    Replies: 2
    Last Post: 12-12-2001, 10:52 AM