• RSS
  • Twitter
  • FaceBook

Security Forums

Log in

FAQ | Search | Usergroups | Profile | Register | RSS | Posting Guidelines | Recent Posts

[Column] Coding Corner 02

Users browsing this topic:0 Security Fans, 0 Stealth Security Fans
Registered Security Fans: None
Post new topic   Reply to topic   Printer-friendly version    Networking/Security Forums Index -> News // Columns // Articles

View previous topic :: View next topic  
Author Message
Stormhawk
Trusted SF Member
Trusted SF Member


Joined: 26 Aug 2003
Posts: 31
Location: Warwickshire, England, UK

Offline

PostPosted: Wed Dec 28, 2005 5:50 pm    Post subject: [Column] Coding Corner 02 Reply with quote

Coding Corner 02: Pick 'n' Mix

December came, and brought with it Christmas, but a distinct lack of discussion in the programming forum. There was no one thing I could pick out this month to elaborate on, though some of the usual C pointer chatter continued, undeterred by the previous Coding Corner. Expect to see more on pointers!

Instead of focussing on one topic, this time, I'm going to concentrate on three topics which I believe were the root of a large number of threads this month: compilers, malloc(), and choosing a programming language for a task.

Compilers

There exist a large number of compilers, for an only slightly smaller number of programming languages. Most of the threads this month about compilers covered specific products such as the javac Java compiler from Sun, or the gcc C compiler.

Java

https://www.security-forums.com/forum/viewtopic.php?t=36204
https://www.security-forums.com/forum/viewtopic.php?t=10691
For Java programs, the compiler needs to know which class contains the main function. In a single-class program, the class should have the same name as the file (without the .java) and should include a main() function. An example is below.
Code:

// Test.java
class Test
{
   public static void main(String[] args)
   {
      System.out.println("Test");
   }
}

To compile this to a .class file using javac, you could simply do the following
Code:

javac Test.java

The .class file created can then be executed using the Java Virtual Machine, as follows.
Code:

java Test

Another commonly used Java compiler is the gcj compiler, part of the GNU Compiler Collection (GCC; not to be confused with gcc, which is the GNU C Compiler, and one of the many front-ends in the collection). The gcj compiler is an ahead-of-time compiler, producing executable code directly. The Java virtual machine is therefore no longer needed to execute such a file.
Code:

gcj -o Test –main=Test Test.java

Note that here you must specify the class which contains the main() function. There is no longer a Java virtual machine to figure this bit out! The program can then be run as follows.
Code:

./Test

For more complex programs involving more than one class, javac will continue to work as above, and will also work if several filenames are listed. When running the program, run the java command with the name of the class containing the main() function. Never add the .class part of the name to a java command! With gcj, the same mechanism for specifying which class contains the main() function will also work.

C / C++

https://www.security-forums.com/forum/viewtopic.php?t=35812
A number of compilers exist for C and C++. The syntax is usually of the following form
Code:

cc -o output_name inputname.c

It is possible to specify more than one input file, if your source is split across many files. Here, cc is a generic name for a C compiler, and often exists on Linux systems as a symbolic link to gcc, the GNU C Compiler.

Other C/C++ compilers include:
Microsoft Visual C++ (Windows)
Intel C++ Compiler (Windows, Linux)
MinGW* (Windows)
Cygwin* (Windows)

* Note: these both use the GCC compiler collection, but provide access to it under Windows

malloc()

https://www.security-forums.com/forum/viewtopic.php?t=36302
The malloc() function provides memory allocation in C. It is used to allocate a memory block of the specified number of bytes. It is closely related to the calloc() and realloc() functions, and should always be teamed up with the free() function!

A call to malloc() returns a pointer to the memory that was allocated (see Coding Corner 01 for a discussion of pointers). The return value from malloc() is always a void*. Many people explicitly cast this to the type they require, though such a cast is implicit in assignment from void* to another pointer type. This is mostly a matter of personal style, though some compilers may warn about this. If the type of the pointer to which you are assigning the result of a malloc() is not specified on the same line, it is probably useful to put the explicit cast in so that anyone reading the code later knows the type it has been converted to.

malloc() takes one argument, the number of bytes to allocate. In the example below, we obtain a file size using fopen() and fstat(), and then allocate enough memory to fit the entire file into – don't try this with large files!
Code:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int main(int argc, char** argv)
{
   FILE* f = fopen(argv[1],"r");
   struct stat s;
   fstat(fileno(f), &s);
   char* c = malloc((size_t) s.st_size);
   /* ... */
}

As this article is not about the stat() function, nor file operations, I'll ignore everything but the malloc() call here. We've created a char* called c, and assigned to it the returned value from a call to malloc(), passing s.st_size into malloc(). s.st_size is the member of the stat result structure which contains the file size. Its type is off_t, which we cast to size_t since malloc() expects a size_t. These conversions are probably implicit on most systems as these various types will almost always be integers.

The char* c now holds the address of the first byte of the memory allocated by malloc(). This can be used as the buffer in a file read operation, or any other operation required.

calloc() is similar to malloc(), but it allocates enough memory for n objects of size s. (Equivalent to a malloc() call with n * s as the requested memory size. calloc() zeros the memory it allocates, whereas malloc() does not.

realloc() can be used to change the size of the allocated memory. It returns a pointer to the newly allocated memory, which may be different to the original pointer passed in. Calling realloc() with a new size of zero is equivalent to calling free() to free the memory.

free() is used to deallocate memory allocated with malloc(), calloc() or realloc(). Calling free on memory which has already been freed results in undefined behaviour, but calling free() on a NULL pointer results in no operation. For this reason, it is recommended that you set any pointer which has just been free()d to NULL,
Code:

char* c = malloc(512);
/* ... */
free(c);
c = NULL;

More information about malloc(), calloc(), realloc() and free() are available on the malloc(3) UNIX manual page.

Choosing A Programming Language

https://www.security-forums.com/forum/viewtopic.php?t=36329
https://www.security-forums.com/forum/viewtopic.php?t=35976
There are many programming languages, some designed to be generic, some designed with a specific goal in mind. Still more were designed for a specific task but have since been extended to allow more general purpose programming. Choosing the “right language for the job” can be a confusing task, at best!

Here, I split the discussion into two categories, general purpose, and specific purpose. I'll cover C, C++, Java, PHP, Perl, Python, Visual Basic and Assembler. Perl and, to a lesser extent, PHP, can be considered under both categories, but I've listed Perl as general purpose and PHP as specific. More about this in their respective discussions.

C – General Purpose

C is an excellent language for developing any type of application. It is a fairly low-level language, providing only the basics. Support for graphics, sound, etc is provided only through third party libraries and operating system integration. Standard ANSI/ISO C will compile on any platform for which a C compiler exists, so a source-distributed program could easily be considered cross-platform, but a binary, compiled program would be tied to a certain operating system and/or architecture. C is the basis of most of the modern languages, and its syntax has propagated through into many of these languages. Learning C is an excellent basis for learning many other languages.

A lot of the complexity of learning C comes from the difficulty of many to grasp the pointer operations which give C so much power. A good book on C is The C Programming Language, Second Edition, by Brian W. Kernighan and Dennis M. Ritchie. Security-Forums.Com reviewed this book at http://www.security-forums.com/forum/viewtopic.php?t=11816

C++ - General Purpose

Derived from C, C++ adds object-oriented support, and a large standard library of useful tools such as containers (vector, list, map) and a string class, which provides many benefits over the C style character array. Again, C++ has no direct support for graphics or sound, but can interface with C and C++ libraries to provide such features. ISO Standard C++ is also platform independent and source-distributed programs should compile on any platform for which a C++ compiler exists.

C++ is a much larger language than C, and introduces a lot more complexity with references, object-oriented approaches such as inheritance, and template programming. C++ is a way to leverage most of the power of C without quite so much effort.

For a book on C++, I recommend The C++ Programming Language, Third Edition (or Special Edition), by Bjarne Stroustrup, the creator of C++. I reviewed this book for Security-Forums.Com at http://www.security-forums.com/forum/viewtopic.php?t=32951

Java – General Purpose

Java is, for the most part, C++ like. It supports object oriented programming but removes much of the complexity which makes C++ difficult to learn (but also more powerful). Java has a large standard library which does include graphics support. The Swing toolkit allows Java programmers to create platform-independent graphical user interfaces.

One major benefit of Java is its use in applets; programs which can be run inside a web browser on a remote computer.

Security-Forums.Com have no reviews of Java books at this time, though I recommend O'Reilly Learning Java, http://www.amazon.com/gp/product/1565927184/002-1000561-5873618

PHP – Specific Purpose

PHP was created for web programming. It is designed to sit on a webserver and process user requests, leading to dynamic websites. PHP provides a lot of built-in functionality for web programming, such as direct access to server variables, URL encoding and decoding, the ability to set HTTP headers and cookies, and much more. Considering that systems such as phpBB, the popular forum system, were crafted from PHP, this language has obvious power and potential for web programming.

PHP has a mostly C-like syntax, but is reasonably easy to learn. Some people also use PHP from a command-line environment to write general purpose programs, and several PHP modules for graphical interface building exist, though PHP is not ideally designed for such use and remains firmly a web language.

For an excellent PHP book, consider either Learning PHP 5, reviewed by myself on Security-Forums.com at http://www.security-forums.com/forum/viewtopic.php?t=35658 or Programming PHP, available at http://www.amazon.com/gp/product/0596006810/002-1000561-5873618

Perl – General Purpose

Perl is ideally suited to data processing. Perl can be used to extract data from a large dataset and generate reports from that data. However, Perl also supports an enormous module set, giving it the power to achieve just about anything conceivable. Perl has long been used by UNIX system administrators for small scripts which glue other, larger programs together.

Many people, even dedicated Perl programmers, will readily admit that Perl can look ugly at times; the syntax is extremely terse, and a Perl program over about 20 lines can be a confusing mess, due to the way Perl allows defaults to remain unspecified in source. Despite this, Perl is an excellent language for small, single-task scripts.

For a great Perl book, Learning Perl will not let you down. I reviewed it on Security-Forums.com at http://www.security-forums.com/forum/viewtopic.php?t=34854

Python – General Purpose

Python is a major contender for Perl's top spot in the scripting world. Python has a vast set of standard modules providing everything from filesystem navigation to a webserver. It has a built in graphical interface toolkit, and the language syntax is easy to read. Python reads more or less like normal English, and even non-Python programmers should be able to work out what most of a Python program does just by reading it, as the language syntax is straightforward and clear.

Python enforces good programming style with its requirement that code blocks be indented. There are no { or } in Python, indentation marks the beginning and end of a code block.

Many large companies use Python extensively. To say that Google make use of Python should prompt many to sit up and pay attention!

When learning Python, the www.python.org website contains full documentation for the language and its standard library, but O'Reilly Learning Python is an excellent book to start out with. I shall be reviewing this book in the coming month.

Visual Basic – General Purpose

Visual Basic (VB) is commonly used by students. It is also used often by those wishing to create small Windows applications which do not do anything particularly processor intensive, as VB makes interface design easy, and provides mechanisms for connecting this into the program logic easily.

Visual Basic is the least portable language discussed here, running only on the Microsoft Windows operating system. I have no recommendation of books for VB, as I have never read any!

Assembler – General Purpose

Assembler, or Assembly Language, is the closest most people will ever get to the language the CPU speaks. Assembler provides a small instruction set which relates directly to the instruction set understood by a processor. Depending on how the assembly code is written, this may be platform-dependent or even operating system-dependent.

For a book on Assembler, try The Art Of Assembly Language, reviewed on Security-Forums.Com at http://www.security-forums.com/forum/viewtopic.php?t=11021

Article by Andrew J. Bennieston. Thanks to capi for spotting a mistake regarding fstat()!
Back to top
View user's profile Send private message Visit poster's website
Display posts from previous:   

Post new topic   Reply to topic   Printer-friendly version    Networking/Security Forums Index -> News // Columns // Articles All times are GMT + 2 Hours
Page 1 of 1


 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

Community Area

Log in | Register