Sunday, January 26, 2014

Pointers in C/C++

Before understanding pointer, it is necessary to understand variable.

Variable declaration
To store any value (for example an integer value 102) in memory, you need a variable. You need to declare the variable before using. Declaration tells compiler that what kind of value you want to store. The declaration also tells the compiler that some space in memory has to be allocated for the variable you declare.
Example of variable declaration:

int num;
char ch;

In this example, there are two variables declared: num and ch. The type specifier int indicates compiler that the num will store integer type and char indicates that ch will store character type.

Scope of variables
Variables have scope: global or local. The global variables have lifespan same as that of the program i.e. the global variables will remain valid for whole lifetime of the program. The memory allocated for the a local variable is valid only for lifetime of the function it is defined in.

int aNum;
int main()
{
  func();
  func();
  return 0;
}
void func()
{
  int x = 100;
}

In this example, aNum is a global variable. It will exist for the lifetime of the program. And the variable declared in func() (int x) will remain valid only if the function func is executing. Also note that the func is called twice from main function. The variable x will be allocated for each call separately. The variables allocated in the first call will be destroyed after the call finishes and in the next call, x will again be allocated.


Value of variables
Any variable you declare in C/C++ has some value. You assign some value to the variable before using it. If you do not assign any value, then it has some random (junk) value. You should never rely on the random junk value. You should always assign a value to variable before using the value of the variable.

In summary:

  • You have to declare a variable before using
  • Variables have values. If you do not explicitly assign a value, they contais random junk values
  • There is some memory allocated for each variable you declare in your program
  • Each variable has some address in memory
  • Variables have scope: global or local


Pointer

A pointer is a type of variable as discussed above but its value has special meaning. Its value contains address of some other variable. Whenever you use a pointer, there are two concepts involved:

  • Pointer variable
  • Pointed memory (whose address is same as the value of pointer)

pointer and pointed memory
The value of pointer variable is address of pointed memory. You can assign any value to pointed memory. Size of a pointer variable is fixed but the size of data at pointed memory can vary.

Declaration of pointers

int* ptr;
char* cptr;

Pointers are declared as type_name * pointer_name; The type_name is used to specify type of memory pointed. In this example, ptr will point to a integer data. That means the ptr is a pointer and its value points to a memory which contains integer data. Similarly cptr will point to some character data.


Assigning values to pointer

There are many ways you can assign value of a pointer

Assign with address of another variable

int* ptr; // declare a pointer variable
int x = 100; // declare an integer variable and assign value of 100
ptr = &x; // assign value of pointer to the address of variable x.
// Notice that the & operator used to get address of a variable

pointer pointing to a variable

In this example the pointer ptr is pointing to the variable x i.e. the value of ptr is address of x. The address of x will vary depending on where it is allocated in the memory. The diagram uses 0xABC just for simplicity.

Assign with value of other pointer

int* ptr;
int* ptr2;
int x = 100;
ptr = &x; // assign value of ptr to address of variable x
ptr2 = ptr; // value of ptr2 is assigned as value of ptr which is address of variable x

pointers

In this example, we first assign the address of x to the pointer ptr then assign the value of ptr to ptr2. After assigning the value of ptr2, both ptr and ptr2 are pointing to the variable x

Assign with memory allocated from heap

int* ptr;
ptr = malloc(sizeof(int)); // malloc allocate memory from heap
// and return address of allocated memory

pointers

In this example, a new memory is allocated from heap and its address is assigned to the ptr. We will discuss more about heap memory later in the post.


Using pointers

Pointers can be used in any expression in two ways:

  • Use the pointer simply by its name. As pointer is a variable, using it by its name will use its value i.e. an address.
  • Use as *pointerName: Using this way will use the value at pointed memory
int x = 100;
int* ptr;
ptr = &x;
printf("%p", ptr); // This will print an address (address of x)
printf("%d", *ptr); // This will print value at pointed memory i.e. value of x i.e. 100.
// Notice that * operator is used to access the data at pointed memory. Do not get confused
// it with pointer declaration. At the time declaration * indicates that the variable is
// pointer and at the time of using the pointer in any expression, 
// * used get the value at pointed memory location


Changing the value at pointed memory
You can change value at the pointed memory using the pointer variable. For example

int x = 100;
int* ptr = &x;
*ptr = 200; // This changes the value at pointed address to 200

In the last line of this example, we are changing the value of pointed memory. Since the ptr is pointing to x, so it will change the value of x. So the value of x will become 200 after the execution of the last line


Unassigned Pointer
What will happen if you do not assign any value to a pointer and try to access the pointed memory? As the pointer is a variable as discussed in the beginning of this post, it will contain some random value if not assigned. That means the pointer points to some random address. If you try to access the pointed memory then

  • You may get access violation. Not all memory addresses are accessible to a program. Please note that you can get the value of pointer (the address) in this case but the problem is for accessing the value at pointed memory
  • You may get/set value at some random memory in your program. This will result in memory corruption.


Null Pointer
If you do not assign any value to a pointer, then it points to some random memory. But there are cases when you will create a pointer variable and not assign any value (pointed memory address) or you will assign the value later. In such cases, you assign the value of the pointer to NULL. NULL is a special value that indicates the pointer is not assigned any value. In your program, you can check if a pointer is assigned to NULL or not. This is a proper way to use a pointer whose value is not set yet.

int* ptr = NULL;
if (ptr == NULL) {
  // you can check if the pointer is set to NULL then do something
}

If you try to access the value at pointed memory for null pointer, then you will get access violation.


Pointer to a pointer
As a pointer can point to any memory location of any variable so it can also point to another pointer. In this case the pointed memory is another pointer.

int x = 100;
int* ptr = &x;
int** ptr2 = &ptr; // Pointer to a pointer. Declared using **
// Using ptr2
// ptr2 will give value of ptr i.e. address of ptr
// *ptr2 will give value at pointed memory by ptr2 i.e. value of ptr i.e. address of x
// **ptr2 is equivalent to *ptr i.e. value of x


Accessing array using pointer

int main()
{
  int arr[4]; // create an array with four elements
  int* ptr = arr; // create a pointer ptr and point to the array's first element
  *ptr = 10; // set the pointed memory (first elemtn of the array) to 10
  ptr++; // change pointer to point to next element in the arrray
  *ptr = 20; // change the pointed memory (second element in array) to 20
}

pointers

You can set value of a pointer to address of an array. In this example, int* ptr = arr; assigns the address of the array 'arr' to ptr. After execution of this statement, the ptr will point to the first element of the array. The ++ on ptr will make the pointer to point to the next element in the array.

Please Note that the ++ operator on a pointer behaves differently than the integer type. The ++ operator on integer type will increment value by one but on pointer it will increment it by size of the type of pointer. In this example, the pointer ptr is of type int (declared as int* ptr) and if we are on 32-bit system, then size of int is 4, then the ++ on ptr will increment its value by 4. That is why the ++ operator makes the pointer to point to next element in the array. On 32 bit system, the arr[4] will be of size 16 bytes. The first element will start at index 0 of the 16 bytes memory, the second element will start at index 4 of the 16 bytes memory and so on. And the ++ operator increasing the value by four making the pointer to point to next element of the array

In the previous example, we assigned the pointer value to the address of an array and manipulated the elements of the array. We can also allocate some memory from heap and treat the allocated memory as array and can manipulate that as an array

int main()
{
  int* ptr = malloc(4*sizeof(int)); // allocate memory from heap to hold
  // four contigious integers. You can think it as dynamically allocated array
  *ptr = 10; // set value of first element of dynamically allocated array
  ptr++; // point to next element
  *ptr = 20; // set value of second element of dynamically allocated array
}


Heap memory
Each program has a pool of memory called heap memory. Whenever you need some memory you can allocate some part of it (the heap) and use. Whenever you are done with the allocated memory, then you can free it. Then it will become unallocated and later can be used by other part of the program. The benefit of heap memory is that it gets allocated on demand. Like global variables, it can be accessed from anywhere in the program. The global variables are allocated when program starts and remain valid till the end of the program. You cannot free global variables.
Example of using heap memory

int* getMem()
{
  int* ptr = malloc(sizeof(int)); // allocate a memory (from heap) of size of integer
  return ptr;
}
int main()
{
  int* p = getMem();
  *p = 100; // Use the allocated memory
  free(p); // Now free the allocated memory
  return 0;
}


Dangling pointer

void  main()
{
  int* ptr = malloc(sizeof(int)); // allocate a memory from heap and set its address to ptr
  *ptr = 100; // sets the value at pointed memory
  free(ptr); // free the pointed memory. Now the ptr does not point to a valid memory 
  *ptr = 200; // try to set value at pointed memory. This is ERROR, you setting
  // value at memory which has already been freed
}

In this example free(ptr) call makes memory allocator to deallocate memory pointed by ptr. If you access the same memory after freeing, it may resuly into unexpected behavior. You will probably corrupt some memory. In this example, after freeing the memory, the pointer points to invalid memory (since it has been de-allocated). This type of pointer is called dangling pointer. You can again set the pointer to to some valid memory and make it non-dangling. But never use dangling pointers


Returning address of local variable

int* func()
{
  int x = 100;
  int* ptr = &x;
  return ptr; // return the address of x. The x will become invalid after the function
  // returns. So the address returns by this function will become invalid
  // after the function returns
}
void main()
{
  int* ptr = func();
  *ptr = 100; // Try to use invalid pointer!!
}

In this example, the function func returns the address of a local variable. As the local variable becomes invalid, after the function returns, you cannot manipulate it after it becomes invalid. The main() function, tries to set at pointed memory (which is invalid at that point of time) which will result in undefined behavior.


Memory leak

void func()
{
  int* ptr = malloc(sizeof(int)); // allocate a memory
  *ptr = 100; // set value at allocated memory
}
void main()
{
  func();
}

In this example, the func() allocate some memory, use it and then returns without freeing it. After returning the function, we have lost the address of allocated memory. The address of allocated memory was stored in a local variable pointer (ptr). The local variable will get destroyed after the function returns. After the function returns, we have no way to access the allocated memory. This situation is called memory leak. In general: if you have allocated some memory and will never use it in future and also not freeing it, then the situation is called memory leak.


Pointer example in linked list
Pointer is heavily used in almost all data structures. Here is a simple example how it is used in linked list. First of all declare a structure to represent a node of the linked list

struct Node {
  int data;
  struct Node* next;
};

The Node struct represents a node of the linked list. The Node contains a data member of type int. The data member can be of any type based on requirement. The second member is of type pointer of type Node. This pointer can point to an object of type Node. It enables a node of linked list to point to another node.

Linked list contain series of nodes in liner fashion. One node pointing to next and the last one pointing to NULL. The NULL pointer indicates that there is no node after. Typically the memory of all nodes of linked list are dynamically allocated from heap memory. We also need a pointer that will point to the first node of the linked list. Let's declare the pointer which will point to the first node of the linked list.

struct Node* first = NULL;

The first is a pointer. So it contains only a address of memory which contains data of type Node. Simply by declaring like this will allocate only the memory for storing the address of actual linked list node. At this point there is no memory allocated for linked list node. Now create the first node of the linked list.

first = malloc(sizeof(struct Node));
first->data = 1; // Notice the -> operator. If a pointer is pointing to a structure object
// and you want to access members of stcuture using the pointer, then -> operator is used.
first->next = NULL;

After execution of these statements, the first pointer will point to dynamically allocated memory. The memory allocated will store a node of linked list. After allocating, we assigned the data part of the node and also set the next pointer to NULL to indicate that there is no node after this node. Let's create another node in the linked list.

struct Node* second = malloc(sizeof(struct Node));
second->data = 2;
second->next = NULL;
first->next = second;

After execution of these lines of code, a memory is allocated for the second node of the list. We set the data and set next pointer to NULL to indicate there is no node after this. And then set the next of first node to address of the second node.

After creating two nodes, the list nodes and pointers can be described by this diagram
pointer


Conclusion

The blog post covered (in short) various aspects of pointer with examples and diagrams. Feel free to comment if you have any question.


Diagrams in this post were quickly drawn using Lekh Diagram. Lekh Diagram is a sketch recognition diagramming app for Android and iOS

Related articles by me: C++ Internals,   C Internals

Wednesday, March 28, 2012

Drawing and erasing using touch on Android

Drawing/Erasing using touch is a common feature in many mobile phone/tablet based apps.
Writing code for this feature is pretty simple for android. Here are steps to do that:
  • add a custom view on which you will draw.
  • process touch event on view.
  • on touch event, record points where touch event occurred.
  • in onDraw method, draw points that were recorded.

Adding a custom view:

We will derive a class from View class for implementing drawing canvas.
And we will add this to UI tree. To add this to UITree, create a LinearLayout in which the
custom view will be added. The LinearLayout is declared in layout xml as:

...... read full blog post and get the code from here: http://blog.avabodh.com/2012/01/drawing-and-erasing-using-touch-on.html



 

Making the iOS text field/view visible which is located under keyboard.

The text view being hidden by keyboard is a very common issue faced by iPhone/iPad developers. When you touch a text view, the text view becomes first responder and keyboard automatically appears. If the text view is lying somewhere in lower part of the screen, most probably it will get hidden under the keyboard.
The solution is to scroll the text view up enough so that it comes above the keyboard. To do that, you need to add the text view in UIScrollView so that it can be scrolled up.

......... read the full blog post and get the code from here: http://blog.avabodh.com/2012/03/making-ios-text-fieldview-visible-which.html


Friday, September 9, 2011

Mounting remote file system using sshfs

sshfs is a tool which mounts remote file system on local machine. It internally uses SSH file transfer protocol. The current implementation of sshfs has dependcny on fuse.

following packages are required to be installed:
sshfs
fuse (fuse-utils on some Linux distros)

On my open suse, fuse package was pre-installed and I needed to install sshfs.

the fuse kernel module has to be loaded before using sshfs. Here is the command to do that
modprobe fuse

I did not require anything to do anything for this on my open suse box because the fuse module was already loaded. This can be easily checked whether a particular module is already loaded or not using lsmod command.

Command to mount remote file system:
sshfs remote-user@remote-server:/remote/directory local-mount-directory


Tuesday, July 19, 2011

/etc/alternatives/

Linux allows different implementation of a single command/utility co-exist. For example you can install both open JDK and sun JDK at a time on Linux and can also make one of them as default. The default selection is made using links in the file system. This works as:-

$which java
/usr/bin/java

$ls -l /usr/bin/java
/usr/bin/java -> /etc/alternatives/java

$ls -l /etc/alternatives/java
/etc/alternatives/java -> /usr/lib/jvm/jre-1.6.0-sun/bin/java

If we type command java on command prompt then /usr/bin/java is invoked. The /usr/java/bin points to /etc/alternatives/java and /etc/alternatives/java points to /usr/lib/jvm/jre-1.6.0-sun/bin/java. So the target of the command java becomes /usr/lib/jvm/jre-1.6.0-sun/bin/java


On Ubuntu, there is a graphical utility which lets you to change/configure the alternatives. But this is missing from the default install of openSUSE. But on the openSUSE this can be easily achieved by command line as -

update-alternatives --config java
 
This command will list all available options and will ask you to enter to select one of them.

Saturday, July 16, 2011

Mounting NTFS drive on openSUSE in read-write mode

Recently, I installed openSUSE 11.4 on my laptop. The laptop is dual boot with windows7. There was a minor issue. The NTFS drive was mounted read only by default. Editing /etc/fstab fixed the issue. Here was the original entry in the fstab:-

/dev/disk/by-id/ata-FUJITSU_MHV2080BH_PL_NW9ZT682CFW0-part2 /windows/D           ntfs-3g    users,gid=users,fmask=133,dmask=022,locale=en_US.UTF-8 0 0

I changed this to as below, to make it working
 
/dev/disk/by-id/ata-FUJITSU_MHV2080BH_PL_NW9ZT682CFW0-part2 /windows/D           ntfs-3g    defaults 0 0

Merging PDF files on Linux

There are many tools out there. gs is one of such command line tools to achieve this. Suppose there are two pdf files as file1.pdf and file2.pdf and we want to merge them into final.pdf, then the command will be -
gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=final.pdf file1.pdf file2.pdf

More than two pdf can also be merged by providing their names in the command line argument.

Sunday, May 22, 2011

Connecting to internet on Linux with Airtel GPRS and Nokia mobile phone

The Nokia phone comes with a software called Nokia PC Suite which provides many utilities including Internet connection on PC via phone. Unfortunately this software is not available for Linux operating system. But, as usual, a little bit of hack can enable Internet connection on Linux using Nokia phone.
Here is what I have tried and it worked for me with Nokia N79 and Airtel (in India) as service provider.
- Install wvdial. It was installed by default on my box (open suse).
- edit /etc/wvdial.conf as
[Dialer Defaults]
Init1 = AT+CGDCONT=1,"IP","airtelgprs.com"
Modem Type = USB Modem
Phone = *99***1#
Password =" "
Username = " "
Modem = /dev/ttyACM1
Baud = 460800
auto DNS = 1
- Now from command prompt, run the command wvdial
- The wvdial will block the command prompt. If want to disconnect, then type Ctrl+C on the command prompt.


Misc:
- I faced an issue. It was not automatically obtaining the DNS address. So Manually edited the /etc/resolve.conf as
nameserver 8.8.8.8
nameserver 8.8.4.4
These two nameservers are public nameserver by google.

- The user name and password here is blank string. There is no user name and password for Airtel. This should be changed accordingly if there is different service provider.

- While connecting the phone to PC, select PC Suite when asked in the phone as "Select USB Mode"

- /dev/ttyACM1 can be different on different machines. run the command dmesg as root just after connecting the phone to PC (by USB) and look for a line similar to

cdc_acm 1-1:1.1: ttyACM1: USB ACM device

Change the device name in the /etc/wvdial.conf to what it appears here




Monday, March 28, 2011

Facebook canvas application and cookie issue with Internet Explorer

The Internet Explorer does not allow cross domain cookies for iframe. This causes the Facebook iframe application to not be able to write Facebook authentication cookie on the client side and it tries to authenticate each time you try to access any page of the Facebook app. This problem does not exist for Firefox.
This can be easily solved using P3P header. Here is how this can be done in PHP
header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
use this code wherever you write some cookie. This is harmless for Firefox.

Zypper/Yast: Download all RPM packages first and then install

Yast is the package management tool in open SuSE and its back-end is zypper. One of frequent issue that I have faced with zypper is that it installs a RPM package as soon as it downloads. It does not download the dependent RPMs before installing a RPM package. Sometime this leads to broken installs if there is some network problem while downloading the dependent RPMs. The problem becomes even worse if there is some network problem while the system update is going on. Once I had a broken update for KDE and I was not able to log into the GUI.
The behavior of zypper can be changed by config file. But I do not understand why the Open SuSE comes with behavior by default. The other popular Linux destro Ubuntu does not have this problem.
Anyway, I here is the solution to the probelm:-
Search for the line
commit.downloadMode
in 
/etc/zypp/zypp.conf
By default this line is commented. Uncomment this line and change it to  
commit.downloadMode = DownloadInAdvance



Tuesday, February 22, 2011

Creating facebook test user account for testing your facebook application

If you are developing some Facebook application then you will need to test it with different user accounts. You will even need network of user account meaning accounts with friends. You would not like to do the testing with your real Facebook account because while testing you might be posting lot of junk data to your wall and this will get published to your friends news feed. You even might require adding new friend and removing friends for the testing purpose.
One option is to create fake accounts. But this is not clean way of doing. You will have to create so many fake email account and you will have to fill lot of fake user info. And another thing is that Facebook deletes fake account once they find it as fake.
There is other clean way of doing. Facebook provide API to create test accounts. These accounts will not be deleted by Facebook. Unfortunately Facebook currently does not provide any GUI to create test account. You will have to use Facebook API to achieve this. 
Here are the things that will be required to achieve this:-
1) A web browser (preferably firefox, I have not tested it on other browsers)
2) wget command line utility. This is freely available and most of the Linux distro has this by default. ( other tools like curl can be used but I am describing here with the help of wget). The reason we use wget is that we need HTTP post method.

Step 1: Get the application access token.
Type this URL in web browser.
https://graph.facebook.com/oauth/access_token?client_id=XXXXXX&client_secret=XXXXXX&grant_type=client_credentials

Replace XXXXX appropriately with your app ID and app secret.

This will give you access token. In the browser you see content like
access_token=XXXXX
Please note down this access token.

Step 2: Create test accounts.
We will need wget command line utility for this. Run this command line utility to create a test user
wget --post-data "installed=true&permissions=read_stream&access_token=TOKEN" https://graph.facebook.com/APP_ID/accounts/test-users
Replace TOKEN with what you got in the step 1 as access token and replace APP_ID with your Facebook application id.
Run this command as many times as many users you want to create.

Step 3: Get the login URL for each users:
Type this URL in you browser
https://graph.facebook.com/APP_ID/accounts/test-users?access_token=TOKEN
Replace TOKEN with what you got as access_token in step 1 and replace APP_ID with your Facebook application ID.

This will give you Info for each test account created. The info also contains login URL. Copy and paste the URL in browser to login into the test user account.

Few more things:
- The login URL is valid for one session only. You will have to repeat the step 3 to get new login URL.
- Access token is gets expired after some time. repeat the step 1 to get fresh access token.
-  Refer the facebook documentation here for more detail
http://developers.facebook.com/docs/test_users/



Monday, February 7, 2011

MySql reseting root password

I was experimenting MySql yesterday and set some password for the root account. But today I forgot. Doing little bit of search on the net, I came across a simple way to reset the password. For this the root access of the OS is needed. Here are the steps:
- Log in as root on the SqlServer box
- stop the MySql server. command: /etc/init.d/mysqld stop
- start mySql in safe mode. command: mysqld_safe --skip-grant-tables
- The previous command will not free the terminal. So from other terminal (command prompt) do these-
mysql --user=root mysql
update user set Password=PASSWORD('new-password') where user='root';
flush privileges;
exit


- Kill the mySql daemon. Command: killall mysqld

- start the mysql daemon. Command: /etc/init.d/mysqld start

Thursday, January 13, 2011

Selecting random record in MySQL

The random number generators are often used in almost all  kinds of application. The random numbers are generated using well known random number generator API. But what about selecting a random record from a database. There are cases we need this. for example- if you want to suggest a random picture to user in a web application. Pictures are stored in database. Fortunately databases provide this kind of feature but unfortunately different databases have different query to achieve this. Here is how this is achieved in MySQL  - 
SELECT columnName FROM tableName
ORDER BY RAND()
LIMIT 1

The value of limit can be changed to number of records to fetch.

Tuesday, January 11, 2011

Scripting langauges

I have always been working with the compiled and statically typed languages like C, C++, Java, C#. I used to avoid scripting languages and also used to hate little bit these scripting languages. But recently started exploring PHP and JavaScript and it changed my perception. Now I started loving these languages. Programming in the these languages needs little bit of different mind set. It takes some time to think in terms of loosely typed coding style.

There are, of course, pro and cons. Here is what I have started observing about the scripting languages -

- You dont need to think in terms of types of data. Most of the time this is very good but some time this is very problematic, especially when you are dealing with string and integer together. In such case you need to explicitly cast to other type. Here is one PHP code which confused me at first glance -
$var = "false";
if ($var) {
echo "This is true";
} else {
echo "This is false";
}

First time when I was dealing with similar code, I was expecting it to print "false". But this prints true. I was thinking, as this is loosely typed language, it will convert the string to boolean automatically. But later found that the string is converted to boolean on the basis of null check. There are other instances, which are potentially confusing. This proves that the these languages are not completely type-less. Sometime you are forced to think in terms of their type and and some complicated rules about the conversion from one type to another.

- You dont need to compile! good or bad?? As I am coming form the background of complied languages, I am feeling this is as a bad thing. The compiler catches lot of error at the compile time but here I have to wait for runtime even for common syntax errors.

- Scripting languages saves you from writing lot of code that you end up writing in languages like Java or C#. Particularly writing the interfaces and thinking what class will implement what interface. As the function name and variable name resolution happens at run time, you can pass around object of any class provided that object
has that particular method or variable with that.

- The scripting language makes your life easier for most frequent operation on string, array, pattern matching etc.

Sunday, December 12, 2010

Translating C to assembly

When you compile a C code, the c compiler translates the c code into assembly language. Then the assembler translates the assembly to machine instruction code.
During my college time (B.Tech from IIIT - Allahabad), I did some reverse engineering of how a C code is translated into assembly by looking into the generated assembly code by gcc compiler.
Now I have put all those things in a form of online book.
Here is the link to the book.

Friday, December 10, 2010

Weak References

Java or .NET has a feature called garbage collection. That means all unreferenced objects will be garbage collected automatically. Does that mean that there can not be memory leak in Java or .NET? If you say Yes, then you are wrong! poorly written Java or C# code can leak memory. For example, if you create a static dictionary and keep on adding object which are not needed anymore. There is common misunderstanding in C# and Java programmer that whatever not needed, will be garbage collected. But the correct statement is what ever not referenced will be garbage collected. Sometime this difference in understanding leads poor code which leaks memory. There is common mistake of some static object holding the reference to some object which is not needed anymore.

Most of the time leak happens in these two cases:
(1) Static object holding reference to object which no more needed.
(2) Object which has long life span holds the reference to object which has shorter life span.

Ideally you can write clean code to avoid these situations. But there are cases it becomes too difficult to maintain such kind of code. A typical example is WPF event handler. If you have registered a event handler, then object that contains the event handler method will be referenced by the event source. Even if the object is not needed, the event source will keep the reference and hence the object will remain in memory. The simplest solution to un-register the event handler.

There another way is to use weak event handler. The weak event handler will keep the weak reference to the event handler target object.

The weak references are the references which are ignored by garbage collector. If the object has only weak references to it, the garbage collector will collect this.

The weak event handler is implemented using the WeakReference class. Here I am describing the WekReference class and the readers can go ahead and implement weak event handler using WeakReference class.

Here is a Java code with WeakReferece usage
import java.lang.ref.*;

public class Weak
{
    public static void main(String[] args)
    {
        Object obj = new Object();
        WeakReference<Object> weak = new WeakReference<Object>(obj);
        checkReference(weak);

        obj = null;
        // setting obj = null makes the object left with
        // only a weak reference to it.
        // although the object has weak reference,
        // the garbage collector will collect this.
        System.gc();
        checkReference(weak);
    }

    public static void checkReference(WeakReference<Object> weak)
    {
        if(weak.get() != null)
        {
            System.out.println("Object Exists!!");
        }else
        {
            System.out.println("Object Garbage Collected!!");
        }
    }
}

And Here is C# code:
public class Weak
{
    public static void Main()
    {
        object obj = new object();
        WeakReference weak = new WeakReference(obj);
        CheckReference(weak);

        obj = null;
        // setting obj = null makes the object left with
        // only a weak reference to it.
        // although the object has weak reference,
        // the garbage collector will collect this.
        GC.Collect();
        CheckReference(weak);
    }

    public static void CheckReference(WeakReference weak)
    {
        if(weak.IsAlive)
        {
            Console.WriteLine("Object Exists!!");
        }else
        {
            Console.WriteLine("Object Garbage Collected!!");
        }
    }
}

Friday, December 3, 2010

The first blog

I am very excited to write my first blog. I have been postponing it from very long time. I never found any reason to start. But recently I found a reason.

Recently I was on a vacation to my village. This was the first time I went to my village with my laptop. In past I always used to avoid carrying laptop with me while I am on vacation. I wanted to be just away from computers for few days. But this time I decided to carry a laptop. In my village I did not have any internet connection, so the laptop was kind of useless. So I decided to do something that can help me pass my time during the vacation. Then I thought to write something. Write what? a blog! yes.. I started thinking what to write in the blog. Then idea came to write some technical stuff. What kind of technical stuff? So many ideas came then finally decided to write something on C++ object model.

This reminded me of my college days. I had a hobby project of writing a OS kernel in C++. During that time I explored a lot about the C++ object model by reverse-engineering. I used to generate assembly code from C++ code then used to study the assembly to figure out how classes, inheritance, virtual functions etc are implemented.

But after long time I had forgotten most of the things. As my job keeps me busy writing code in C# only, I was out of touch in C++. But again the same process helped me. As I had the laptop with me. I started looking at the disassembled code and recollected most of the things that I explored during the college days.

Then I started writing. Initially I thought to write some blog-post only. But the content became too big to be fit for a blog post. So I decided to write as online book on some website.

By the time I had a rough-draft, my vacation was over. After the vacation, I spent some time to find a domain and then put my stuff there. Again, this is the first time I was making a website. Although I am not new to HTML but I am not good at making web-pages. I found some free web template from the internet and used that for my web site.

After this, it took me few more days to add my all stuff to HTML and post it to the website. I covered most of the topic of the C++ object model, but still few things are left. These are exception handling, run time type identification, object copy and copy constructor, pointer to member function. I will add these topics later.


Here is the link the book.

I guess this is enough for my first blog post.