Technical Interview

Tips, questions, answers and puzzles at
www.technical-interview.com

Wednesday, June 30, 2010

How do you do dynamic memory allocation in C applications? List advantages and disadvantages of dynamic memory allocation vs. static memory allocation.

How do you do dynamic memory allocation in C applications? List advantages and disadvantages of dynamic memory allocation vs. static memory allocation.

Answer:


In C, malloc, calloc and realloc are used to allocate memory dynamically. In C++, new(), is usually used to allocate objects. Some advantages and disadvantages of dynamic memory allocation are:

Advantages:

• Memory is allocated on an as-needed basis. This helps remove the inefficiencies inherent to static memory allocation (when the amount of memory needed is not known at compile time and one has to make a guess).

Disadvantages:

• Dynamic memory allocation is slower than static memory allocation. This is because dynamic memory allocation happens in the heap area.
• Dynamic memory needs to be carefully deleted after use. They are created in non-contiguous area of memory segment.
• Dynamic memory allocation causes contention between threads, so it degrades performance when it happens in a thread.
• Memory fragmentation.

What are references in C++? Why do you need them when you have pointers?

What are references in C++? Why do you need them when you have pointers?

Answer:


A reference variable is actually just a pointer that reduces syntactical clumsiness related with pointers in C (reference variables are internally implemented as a pointer; it’s just that programmers can't use it the way they use pointers).

As a side note, a reference must refer to some object at all times, but a pointer can point to NULL. In this way, references can be more efficient when you know that you'll always have an object to point to, because you don't have to check against NULL:
void func(MyClass &obj)
{

obj.Foo();

}
Is better than:
void func(MyClass *obj)
{

if (obj) obj->Foo();

}

What leads to code-bloating in C++?

What leads to code-bloating in C++?




Answer:

Inline functions and templates, if not used properly, may lead to code bloating. Multiple Inheritance may also lead to code bloating (this is because the sub classes will end up getting members from all the base classes even if only few members will suffice). Techniques to avoid code blot are discussed in “Effective C++ programming”.