Wednesday, April 21, 2010

Exception vs status returns

From: http://nedbatchelder.com/text/exceptions-vs-status.html

Exceptions provide richer error information

Status codes take valuable channels: 1 return value

Cannot return status codes in implicit code: constructors/destructors

Status codes can go unchecked

Exceptions can cause explicit complexity

Exceptions are invisible in the source code

Exceptions create too many possible exit points for a function


Tuesday, April 20, 2010

Hashtable (hashmap)

Description
a data structure that uses a hash function to efficiently map certain identifiers or keys (e.g., person names) to associated values (e.g., their telephone numbers). The hash function is used to transform the key into the index (the hash) of an array element (the slot or bucket) where the corresponding value is to be sought.

Advantages
+ Speed

Drawbacks
- Hard to get efficient hash function
- Hard to enumerate values

Example
+ Person name to phone number lookup
- Spell-check application - not sorted

Monday, April 19, 2010

Find the largest subsquence

Difference between non-virtual and virtual function

Non-virtual function calls are resolved at compile time. Virtual function calls are dynamically resolved.

Friday, April 16, 2010

sql query

Given the following tables, write a query to display all people who do not like the bears.
create table PEOPLE (
NAME varchar(20),
primary key NAME
);
create table TEAM_LIKES (
NAME varchar(20),
LIKES varchar(20),
foreign key NAME references PEOPLE (NAME)
);
Answer:
select distinct PEOPLE.NAME from PEOPLE where PEOPLE.NAME not in (select
NAME from TEAM_LIKES where LIKES='bears');

Monday, April 12, 2010

Stack direction

From: http://kstruct.com/2007/04/16/interview-questions-stack-direction/

Stack Growth : How would you find out if a machine’s stack grows up or down in memory?

Well, it’s fairly simple to write a C program to test this. Obviously I’m assuming that a C compiler is available. The following program creates an integer (a) on the stack, then passes a pointer to a down to the function sub. sub creates another integer on the stack (b), then compares the address of a to the address of b. If b’s address is greater then a’s, then the stack is growing up, if it’s less, then it’s growing down.

#include <stdio h>

void sub(int *a) {
int b;

if (&b > a) {
printf("Stack grows up.");
} else {
printf("Stack grows down.");
}
}

main () {
int a;
sub(&a);
}

Wednesday, March 31, 2010

What are the methods in Object?

clone, equals, wait, finalize, getClass, hashCode, notify, notifyAll, toString

Tuesday, March 30, 2010

Java memory leaks

http://www.ibm.com/developerworks/library/j-leaks/

You can prevent memory leaks by watching for some common problems. Collection classes, such as hashtables and vectors, are common places to find the cause of a memory leak. This is particularly true if the class has been declared static and exists for the life of the application.

Another common problem occurs when you register a class as an event listener without bothering to unregister when the class is no longer needed. Also, many times member variables of a class that point to other classes simply need to be set to null at the appropriate time.

Monday, March 22, 2010

Java final keyword

http://en.wikipedia.org/wiki/Final_(Java)

Final Classes - cannot be subclassed
Final Methods - cannot be overridden in a subclass
Final Variables - cannot be reassigned

Bonuses:

finally - The finally block always executes when the try block exits

Object.finalize() method - Before the invalid objects get garbage collected, the JVM give the user a chance to clean up some resources before it got garbage collected.

Difference between abstract class and interface?

From: http://java.sun.com/docs/books/tutorial/java/IandI/abstract.html

Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead.

Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they are related to one another in any way. Think of Comparable or Cloneable, for example.

By comparison, abstract classes are most commonly subclassed to share pieces of implementation. A single abstract class is subclassed by similar classes that have a lot in common (the implemented parts of the abstract class), but also have some differences (the abstract methods).

What does the volatile keyword do in C/C++?

http://www.embedded.com/story/OEG20010615S0107

Wednesday, March 3, 2010

What are ways to allocate memory in C?

// allocate memory of size
void *malloc(size_t size);

//allocates a region of memory, initialized to 0, of size nelements × elementSize
void *calloc(size_t nelements, size_t elementSize);

// resizes allocated memory
void *realloc(void *pointer, size_t size);

// unallocates memory
void free(void *pointer);
Passing non-allocated memory (i.e. not allocated by malloc, calloc, or realloc) to free will result in undefined behavior

Monday, March 1, 2010

How to capture signals from bash

From: http://www.davidpashley.com/articles/writing-robust-shell-scripts.html

Setting traps

Often you write scripts which fail and leave the filesystem in an inconsistent state; things like lock files, temporary files or you've updated one file and there is an error updating the next file. It would be nice if you could fix these problems, either by deleting the lock files or by rolling back to a known good state when your script suffers a problem. Fortunately bash provides a way to run a command or function when it receives a unix signal using the trapcommand.

trap command signal [signal ...]

There are many signals you can trap (you can get a list of them by running kill -l), but for cleaning up after problems there are only 3 we are interested in: INT, TERM and EXIT. You can also reset traps back to their default by using - as the command.

SignalDescription
INTInterrupt - This signal is sent when someone kills the script by pressing ctrl-c.
TERMTerminate - this signal is sent when someone sends the TERM signal using the kill command.
EXITExit - this is a pseudo-signal and is triggered when your script exits, either through reaching the end of the script, an exit command or by a command failing when using set -e.

Usually, when you write something using a lock file you would use something like:

if [ ! -e $lockfile ]; then    touch $lockfile    critical-section    rm $lockfile else    echo "critical-section is already running" fi

What happens if someone kills your script while critical-section is running? The lockfile will be left there and your script won't run again until it's been deleted. The fix is to use:

if [ ! -e $lockfile ]; then    trap "rm -f $lockfile; exit" INT TERM EXIT    touch $lockfile    critical-section    rm $lockfile    trap - INT TERM EXIT else    echo "critical-section is already running" fi

Now when you kill the script it will delete the lock file too. Notice that we explicitly exit from the script at the end of trap command, otherwise the script will resume from the point that the signal was received.

A slightly more complicated problem is where you need to update a bunch of files and need the script to fail gracefully if there is a problem in the middle of the update. You want to be certain that something either happened correctly or that it appears as though it didn't happen at all.Say you had a script to add users.

add_to_passwd $user cp -a /etc/skel /home/$user chown $user /home/$user -R

There could be problems if you ran out of diskspace or someone killed the process. In this case you'd want the user to not exist and all their files to be removed.

rollback() {    del_from_passwd $user    if [ -e /home/$user ]; then       rm -rf /home/$user    fi    exit }  trap rollback INT TERM EXIT add_to_passwd $user cp -a /etc/skel /home/$user chown $user /home/$user -R trap - INT TERM EXIT

We needed to remove the trap at the end or the rollback function would have been called as we exited, undoing all the script's hard work.