Saturday, September 24, 2011

new instead of malloc

While searching I found a very naive, but useful thing about new/malloc.

Why should we use new instead of malloc ?

  1. New and Delete makes sure that constructors and sestructors are called but not the case with malloc and free functions of C. 
  2. Pointer conversion safety: malloc() returns a void* which isn't safe. new returns a pointer of the right type. 
  3. new is a Operator: new is an operator that can be overloaded for better memory management by a class, while malloc() is not an operaotor. 
  4. new operator computes the size of object automatically whereas malloc cannot.
  5. It is possible to initialize the object while allocating memory with new. 
  6. Its possible to construct an object over an already allocated memory using another version of 'new' operator known as 'placement new' operator. While with malloc() it is not possible.

Friday, September 16, 2011

Nth last element in Linked List (C++)

The following code shows how to get nth last element in a linked list. It uses a queue to hold the temporary elements.

Algorithm:-
1>Make a queue of length N
2>Traverse the linked list from root
3>While traversing, en-queue first N elements
4>After this for en-queuing every element, de-queue another element.
5>When we reach the end of linked list, the last de-queued element will be the Nth last element.



Output:-

Tuesday, September 13, 2011

CountDown Latch to measure sorting time (java)

The following code uses CountDown Latch to measure the performance of sorting example. The sorting method sorts n array of random numbers in separate threads.