Thursday, September 25, 2008

Segmentation Fault

One of the most common errors in C programming, which happens during pointer exception. The program is trying to access memory that does not belongs to it. This is similar to Java's version of NullPointerException.

For example if we do this in C,
char *s = "hello world";
*s = 'H';


When the program containing this code is compiled, the string "hello world" is placed in the section of the program binary marked as read-only; when loaded, the operating system places it with other strings and constant data in a read-only segment of memory. When executed, a variable, s, is set to point to the string's location, and an attempt is made to write an H character through the variable into the memory, causing a segmentation fault. (from wiki)

I had a similar problem such as:
char *s = "123";
int num = (int) *s;


I solved this problem using atoi(); which converts the ASCII characters into int.
char *s = "123";
int num = atoi(*s);

Monday, September 22, 2008

Makefiles in C

Typically in most c programs (especially those written for opensource purposes), there exist a file call Makefile. Makefile is pretty much like a macro (for those familiar with Microsoft Office), or a batch file (for those familiar with DOS). Well basically, in very simple terms, it automates repetitive stuffs so that it makes life easier to program.

In a huge program, we tend to have many classes and dependencies (i.e. header files). For example, if we have a single program4 file which is make up of program1.c, program1.h which in turn make up program2.c together with program3.c to make the final program4 file.

In this example, the modification of program1.c will result in a recompilation of program1.c and program3.c which is technically inefficient. Imagine having to do this each time you are trying to debug and found a bug. So to make life easier, Makefile comes to the rescue. It basically automate compilation so that we don't have to type a long string of dependencies from scratch each time we make modification.

For a proper tutorial on how to create your own Makefile, visit:
http://www.eng.hawaii.edu/Tutor/Make/3.html

In very short term, in order to execute the makefile, run the command "make" inside a folder.
Yes, correct, just type
"make" and hit ENTER. A chunk of output should normally appear, type "ls" and the executable program (normally in green) can be seen.

Compiling in C with Headers

While compiling a program using gcc is easy, compiling with headers (multi source) is not that clear cut at all. I visited various tutorials but none gave a clear description as to how do you compile a program with header files, so here i am creating one :)

A bit of details about header files, its similar to that of interface in java. Basically, its part of an object oriented concept that allows you to separate your program logic from other developers, the purpose really, is to allow other developers to know input and output information about your program (nothing much about the internal program logic) so as to allow other developers to develop their own program independently while you write your part.

Consider the following example:
We are trying to create a calculator program, we have a few programmers working on different components, one of which is multiplication. While developing the main calculator program (calculator.c), someone else can work on multiplication program logic (Multiplication.c). In a Multiplication there is an input of integer and and output of integer. Therefore, we can create a Multiplication.h file that specifies the method that the main calculator program developer should call in order to get the multiplied value of an input.

These are the files that forms the story above,
Multiplication.c
#include <stdio>
#include "Multiplication.h"
int getMultiply(int var1, int var2) {
return var1 * var2;

}

Multiplication.h
int getMultiply(int var1, int var2);

Calculator.c

#include <stdio>
#include "Multiplication.h"

int main() {
printf ("Result of 2 x 2: %d", getMultiply(2,2));
return 0;
}


As we can see clearly above, the method getMultiply inside Multiplication.h does not include any details of the internal logic of the multiplication method. To use a custom header, you have to include it within the main program as shown in line 2 of Calculator.c and call it as if the method is local within the program.

How do we actually compile the program?
1. compile the header's c files (not the header file):
gcc -c Multiplication.c
You can use the -c option with gcc to create the corresponding object (.o) file from a .c file. By specifying -c, the compiler will stop after the assembler stage, you will see that the output will be Multiplication.o.


2. compile the main program
gcc -o Calculator Calculator.c Multiplication.o
Here we specified the output to be called Calculator and we specified the input file of Multiplication.o which we generated from step1.

3. we can now run the program using:
./Calculator
If the program does not execute, and throws a permission error, try "chmod 755 Calculator"

Right. That's all folks.

I found a good lecture after posting this!
http://www.eng.hawaii.edu/Tutor/Make/1-4.html

Random Linux Commands

cp - copy files from one place to another
chown - change owner of the file or directory
chmod XXX - change the access permission to the file or directory
ls -all - list the entire directory and files information
rm - remove filename
rmdir - remove directory
apt-get install - install the filename of the specified package name
apt-get update, - update the existing repository list specified in /etc/apt/sources.list
apt-cache search - search the list of packages by the term specified

GIT Repository

GIT is pretty much like a repository to faciliate sharing of work amongst developers (mostly), you need to know this if you are looking at open source development, let me introduce a few commands that may potentially be useful:

1. git clone - this clones the directory of the repository.
e.g. git://scarlet.aura.cs.cmu.edu/openisr.git

2. git push - this pushes the files from your local drive to the central repository (the default is master for the first file) If there are some errors, in regards to non-fast-foward, use the -f option.
e.g. ssh://aarontwc@scarlet.aura.cs.cmu.edu/~aarontwc/openisr.git master

http://davitenio.wordpress.com/2008/10/08/synchronize-git-repositories-between-deskop-and-laptop/

3. git add . - this command adds the existing files in the correct directory to be commited. Basically, it specifies the files to be committed into GIT.

4. git commit -m "message to commit", (instead of just typing git commit, having the -m parameter, allows you to put meaningful text messages to commit, so that its easier for you to track your changes later.

5. git show - this command allow you to see the list of commits make, when and why


6. git pull - this command pulls the latest updates to your local repository.

Kernal.org has a comprehensive guide on GIT.

VIM Editor

An alternative to the EMACs/Nano (my favourite), due to the usage of GIT, (a CVS program), i have to start learning VIM, here are some useful commands to remember.

1. There are different modes in this editor. To get into editing mode, we need to hit "i", (which is the equivalent of insertion. To escape from editing mode after we are done, we need to hit the 'ESC" key which will then bring us to the main prompt.

2. It allows us to do stuffs faster here in he main prompt, for example, by typing "d" on a line, it allows us to remove the entire line.

3. To save, type, "ZZ" (Shift + Z + Z) or use ":x" (Colon + x + ENTER), this qill automatically save and quit. To quit, go outside insertion mode (press ESC), and then type "ZQ" (Shift + Z + Q) or ":q!" (Colon + q + ! + ENTER). The program will quit without saving.

4. To do more complete stuffs like after being able to recover from a lost SSH connection, look under the area of a swap file. When we try to access the file, it will say something like the file already exist. do you want to edit, recover, delete, quit or abort.

Try the following steps to recover the files or do side by side comparion of iles
1. hit "r" when it asked what you want to do (to recover)
2. :sav! /tmp/%
3. :vs
4. :diffthis
5, CTRL + W + I
6. :bp
7. e (to edit anyway)
8. :diffthis (finds the difference between the two files side by side)

Right that should be all you ever need to know about VIM for basic usage.

Java Problems

Today while coding in java, I ran into two problems.

1. My controls are dynamically generated during runtime. i.e. I have a JTextPane (txtPane) and JButton (btnGenerateRandomNum). Say for example, when btnComment is clicked, I want to paste a randomly generated number into that particulat txtPane. (there are like 20 txtPane each with its own JButton). The question is, on receiving an event from JButton how do I actually go back to the correct txtPane and display the generated random number?

a. first of all you need to create a public list of Jpanels generated
private ArrayList panelList = new ArrayList();

b. add actionCommand with a counter, counter will serve as a unique identifier to the button generated by the java codes. Add this button to the panel and store the panel into the list.
btn.setActionCommand("annotate"+counter);
panel.add(btn);
panelList.add(panel);

c. under actionPerformed method, check that the command received starts with annotate, if it starts, obtain the button ID, based on that, we can obtain the panelList by index. Cast that into the control type you want, in this case, JTextPane, we specify that we want the first component in the JPanel by specifying the index as zero.
if (command.substring(0,8).equals("annotate")) {
int buttonID = Integer.parseInt(command.substring(8))
JPanel tmpPanel = (JPanel) panelList.get(buttonID);
JTextPane tmpArea = (JTextPane) tmpPanel.getComponent(0);
tmpArea.setText= "Yes Success!";

}

The three steps above, allowed us to very simply access controls that were dynamically generated by storing it in an arrayList and getting it back, setting values to it.

[edited, 23rd september]

2. I placed these generated controls into a panel then into a container (with scrollpane). I set the container layout to be BoxLayout. So whenever i click the button "new", a new Panel is inserted into the bottom of the container. This function works perfectly. But it dynamically resizes, i.e. since the height of the container is 500, by pushing the button, it will show 2 panels in correct sizes, by the time i reach the 3rd panel, the panels are resized automatically smaller. (it is trying to fit the size of the container)The question is how do i actually do something like this so that the panel don't resize itself? I tried flowlayout but it does not work correctly (the panel does not appear). I am not sure if there are any layout that I didn't know that works how i need it to - basically to display things from top to bottom (vertically) and don't resize it. Just like how a normal row is added in a table using PHP.

verContainer.setLayout(new BoxLayout(verContainer, BoxLayout.Y_AXIS));
verContainer.add("panel" + counter, inputPanel);
verContainer.setPreferredSize(new Dimension(500,200* counter));

Basically, to prevent dynamic resizing due to the container size, I increase the container size at the same time so that the box layout works perfectly without resizing.