Tag Archive for 'c'

Yet Another Transition

After 4 happy years of coding in compiled languages of C and C++, the time has come to make a transition to the interpreted language of Java. The change is more of an imposed one than desired. And I am not getting drawn into the subject of compilers vs. interpretors, mainly because of my lack of experience with the latter category.

Starting the next week, I shall join the FICO, Bangalore. I am quite excited about the oppurtunity as I have received excellant inputs from my seniors and their friends regarding the kind of work that people do over there. Also I need a change from an university-like environment.

Now at Fair Isaac, apparently, people prefer Java over C++. Navin sir said that there are a group of people using C++, but the bulk of libraries and code is in Java. So it will be easier if I switch over to Java than C++, though it shouldn’t be a lot tougher sticking with it. And after giving it a thought, I have decided to learn Java. Learning a new programming language is all about going through its libraries and adapting them. It should be an easy enough task. Also since I have a basic understanding of objects, classes, inheritance and theior abstract nature, it should be easy enough.

The only thing I shall miss are the pointers. Sadly Java does not allow pointer access to programmers like the C does. I do not know the reason behind this restriction, but it sure makes me sad. Of late, most of my variables were being referenced by address and I was really getting into the habbit of using pointers. They make complicated things so easy to manage.

And then another thing is the usage of WIndows. I would really prefer Ubuntu for coding. I do not thing there should be any problem with using ubuntu. I just do not want to START to TURN OFF windows :P .

I Hate Segmentation Faults

I have  been coding in C for four years now. Any C user knows the segmentation fault error. And trust me, there cannot possibly be anything worse than seeing your program terminate with a seg fault message. It irritates me so much that in my B Tech Project program I have created a signal handler which catches the error and prints a happy message instead of the boring default message.

This is what I have done :

// Include signal.h for signal handling
#include <signal.h>

/**
  * The function which is called upon a seg fault
  */
void SignalHandler(int sig) {
  printf("\n\nHave a happy time debugging. Good luck :D \n\n");
  exit(-1);
  return;
}

/**
  * The main function. Declare the signal handler here.
  */
int main(int argc, char *argv[]) {
  signal(SIGSEGV, SignalHandler);

  /**
    * Do whatever you want to
    */

  return 0;
}

:) . I know this doesn’t do anything, but atleast I do not feel frustrated now.

A Logger In C

Now I am working on this fair scheduling for my B Tech Project (BTP). Already having written a 1000 lines of code, it is a great pain to debug it. More so if you do not know which function might have caused the error. I needed a logger which could log all the events. The events include entering a function, any important calculation/decision it makes, any return values, so that if my program breaks down I can exactly pinpoint the source of error simply looking at the log file generated.

I have no idea if any inbuilt logging functionality exists for C programs or not. Either way, I did not have much time to google up and learn how to use it. I decided to make my own logger, a simple one, which would serve my purpose. It hardly took me 10 minutes to get over with it.

One of the important functionalities that I wanted my logger to have is indentation. The log should be properly indented, just the same way as we indent the code. When the program control enters a new function, the logging should get indented to right, and when it leaves the function, the logging should get indented by the same amount to the left. So I defined two macros, INDENT and OUTDENT. To make them work, I defined a global variable – logIndent. The logIndent would at any given time contain the amount of space by which the log has to be indented. Obviously, I initialized it with 0. Also defined is a global variable called indentVal which is the amount of spaces with which the indentation should take place. I like the value to be 2. The two macros are

#define INDENT logIndent += indentVal
#define OUTDENT logIndent -= indentVal

int indentVal = 2;
int logIndent = 0;

I defined another macro called SPACES which would print the number of spaces to produce the required indentation.

int tempIndent;
FILE *logFile;
#define SPACES for(tempIndent = 0; tempIndent < logIndent; tempIndent++) fprintf(logFile, " ");

Obviously tempIndent is a globally declared temporary variable and logFile is the file pointer to the file where the log has to be written. I initialize the logFile pointer in the main() part of my program.

And finally coming to the logger, I created a custom printf() statement using the vprintf() command. I call my logger as LogThis(). Its declaration is as follows

void LogThis(const char *format, ...);

It is constructed as follows

void LogThis(const char *format, ...) {
  va_list args;
  va_start(args, format);
  SPACES;
  vfprintf(logFile, format, args);
  va_end(args);
}

That’s it ! To use this logger, I have to do the following in my function :

#include <stdio.h>
#include <stdarg.h>
void TestLogger() {
  int returnVal;
  float retVal;

  LogThis("<TestLogger>\n");
  INDENT;

  /**
   *  Inside the function do whatever you want to
   */

  LogThis("Returns: %d, %f\n", retrunVal, retVal)

  OUTDENT;
  LogThis("</TestLogger>\n");
}

Done ! A well indented log will be produced. This has really helped me debug the code. I do not have to gdb from the last point that worked in my program. Instead, I know which function the program control was in when it threw an error. I need to gdb from that function onwards only, thus reducing the debuging time considerably. Also, in case of errors, I can increase the debugging data for that particular function, thus eliminating the need to use gdb at all.

Variadic Functions

C is a beautiful language. Though I have been using it for a few years now, I have yet completely mastered it. Just now, I stumbled across what are called variadic functions.

Have you ever wondered how to write functions that take in variable numbers or arguments? Take for instance printf() or scanf(). Both have been implemented in C. These are called variadic functions.

Problem: To construct a function which can take variable number of inputs, eg; printf()

Solution:

Its a simple matter of using built in macros defined in the stdarg.h library. It provides the following macros:

  • va_list: The list of argument
  • va_start: Initializes va_list to the first unnamed argument
  • va_arg: Takes the current variable and the type
  • va_end: Called at the end

Through a self explaining example I would like to demonstrate the usage of these macros. Let us define a new function called PBAPrint() which imitates the printf() function.  For example,

PBAPrint(”df”, 12, 2.2) outputs: int = 12 float = 2.2

PBAPrint is implemented as follows:


void PBAPrint(char *format, ...) {
  va_list ap;

  va_start(ap, format);

  while(*format) {
    if(*format == 'd')
      printf("int = %d ", va_arg(ap, int));
    else if(*format == 'f')
      printf("float = %f ", va_arg(ap, float));
    else {
      printf("unsupported format ");
      break;
    }
    format++;
  }

  va_end(ap);

  return;
}

But apparently things are much more simpler when using C++.




Theme Tweaker by Unreal