Interview Question: C++ Memory Allocation

Sample Question #315 (programming – C++)
 
Discuss the validity of using malloc() or calloc() for memory allocation in C++. Why or why not would you use these functions?
 
[This is a very popular question. Hint: how does C++ create objects and how is it different from C?]
Advertisements
This entry was posted in Sample Qs. Bookmark the permalink.

2 Responses to Interview Question: C++ Memory Allocation

  1. Zemin Lee says:

    Constructor, right?

  2. Frank Kelly says:

    In C, dynamic memory allocation to the heap* (not the stack) is done via the following commands:
    malloc – allocates a specific number of bytes
    realloc – increases or decreases the allocated “chunk” of memory, reallocating if necessary
    calloc – allocates a specific number of bytes and sets all to zero
    free – releases the block of memory back to the system.

    C++ is backwards compatible with all of these so they can be used; however the commands have been largely superseded by “new” and “delete” commands in the newer language which respectively (a) allocate/assign a value and (b) free up memory on the heap. Be aware that any ‘dangling’ pointers should be later removed (by setting to zero, for example) upon deletion of the chunk of memory pointed to.

    * The heap is an area of memory set aside for the programmer to use and manually allocate to.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s