Oct 012013
 

Interview Question…

I have following code snippets…

Code snippet 1
int arr[1000000];
int main()
{   
	return arr[0];
}
Code snippet 2:
int arr[1000000] = {10};
int main()
{   
	return arr[0];
}

After compilation of the above snippets the output exe differs in size. The second snippet’s executable is much bigger in size than the first snippet’s executable. See screenshot…

image

Why?

 

Sep 162013
 

C++ Technical Interview Question

Is there a bug in the following C++ code snippet?

class Base
{
public:
	Base()
		: m_pBaseIds(new int[200])
	{
	}

	virtual ~Base() { DelPtrs(); }

protected:
	virtual void DelPtrs()
	{
		delete [] m_pBaseIds;
	}

private:
	int* m_pBaseIds;
};

class Derived : public Base
{
public:
	Derived() 
		: m_pIds(new int[100])
	{

	}

protected:
	virtual void DelPtrs()
	{
		delete [] m_pIds;
		__super::DelPtrs();
	}

private:
	int* m_pIds;
};

I’ll post my answer in a while once interested people post some answers. This is a pretty easy one for experts but a real good one to check OO basics of C++ candidates.

My Answer

Yes there is a bug. Its a memory leak, be aware that a virtual function call from a constructor/destructor will not behave as expected. The call will not call the implementation in the derived class. You’ll not get an error message either. You’ll take notice of the bug only until the memory starts growing, god forbid this happens in production environment. You’ll end up having to call me up. :) The correct way to fix such issues is to use the C++ STL classes or the equivalent language collection classes to avoid direct memory allocation. The other and probably the ideal way to fix this issue is to let the allocator be the de-allocator. So if derived is allocating then let derived do de-allocation.