Tuesday, June 9, 2009

std::ostringstream AKA String Streams...

Want to share a few bits about a very important and useful feature of standard library today. std::ostringstream can come in handy in many situation. You know we often need to concatenate strings. And often it becomes tedious, usually this is done using strcat funtion in C and + operator in C++  std::string class . For example

// C style

char * szFullName = strcat("First Name ", " Last Name");

//C++ style
std::string strFirstName = "First Name";
std::string strLastName = "Last Name";
std::string strFullName = strFirstName + " " + strLastName;

std::ostringstream gives us a convenient way to build strings conveniently.
std::ostringstream provides functionality very much similar to sprintf function of C language.

Like for example you got names, ages, and heights of a few kids stored in arrays and you want them to be printed nicely on screen. Perhaps you could use a std::string and + operator to join string but I think using ostringstream will be a better approach.

Preview (hint: you can copy and paste the preview into Microsoft Word):
const int CONST_ARRAY_SIZE = 3;
std::string aryStrNames[CONST_ARRAY_SIZE] = {"Ali", "Jason", "Shiv"};
int aryNAges[CONST_ARRAY_SIZE] = {5,9,11};
float aryFHeight[CONST_ARRAY_SIZE]={3.2,4.0,4.4};
std::ostringstream outBuffer;
for(int i = 0; i < CONST_ARRAY_SIZE; i++){
outBuffer<<aryStrNames[i]<" is " << aryNAges[i] << " years old, and his height is "<< aryFHeight[i] << endl;
}// end for i
cout<< outBuffer.str();

Here's a link to ostringstream on C Plus Plushttp://www.cplusplus.com/reference/iostream/ostringstream/

Tuesday, March 17, 2009

Working with std::string::substring() method

Though it is a very simple function, but sometimes people(me too) make a mistake when coding thing up. For example we have a std::string strHello

int nPositoinOfSemiColon = strHello.find(";", 0);

find method will find the fist parameter ";" in strHello, starting from second parameter i.e. 0.
Now the nPositoinOfSemiColon will contain either string::npos which means the string provided to find method was not found in strHello. Or in our case, 5 which is the location of ";".

strHello.substr(0, nPositoinOfSemiColon );

will return "Hello", i.e. 5 characters starting from location 0 in strHello.
Now consider

int nPositionOfSecondSemiColon = strHello.find(";", nPositionOfSemiColon);

Well... writing following line of code will... wonder what...

strHello.substr(nPositionOfSemiColon, nPositionOfSecondSemiColon);

CAUSE AN ERROR!!! FOLKS!!! ERR GRR ERROOORRR... a vicious cruel ugly error... heh heh heh...
Poor baby programmers will asK "But why Uncle why???"
Because, of the values in variables at this time are...

nPositionOfSemiColon = 5
nPositionOfSecondSemiColon = 11
That means
strHello.substr(5, 11);

i.e. extract 11 characters starting from location 5 in strHello.
Whereas, 11 is total length of strHello...

The right way to go is

nPositionOfSecondSemiColon - nPositionOfSemiColon);

That means
strHello.substr(5, 6); // That means ";WORLD"

Cheers folks... have fun... remember... coding is a noble pursuit... so just keep hitting it hard... savor the wonders and joys of turning real world into programming language codes, and bear the tensions with enough tolerance...

More C/C++ Interview Questions

I was keeping this post on hold for almost a month, so that I will post the questions along with the answers... but due to some reasons, I was unable to post the answers...
Will do it some time later in future...
For the time being, the C/C++ interview questions are given below...
If anybody finds out an answer, feel free to write it in comments...

1. What is the difference between a pointer and array?
2. Is it possible to find out the size of an array?
3. What is NULL?
4. How can we find if a pointer contains a valid value or not?
5. We have a circular linked list, and its tail -> next is not pointing to List -> Head. How can we diagnose such an error condition?

Monday, March 9, 2009

A tricky error, when using std::string with *printf funtions

All of us know what this code (listing 1)will do...

char * szName = "Ex";

printf("%s", szName );

Will anybody tell what will be the result of these lines(listing 2)...

std::string strName = "Zed";
printf("%s", strName);

Ladies and gentlemen... listing two will cause your program to crash. This is a very common mistake made by programming newbies... though an experienced pro may also do the same...

The right way to print the string is

std::string strName = "Zed";

printf("%s", strName.c_str());

such errors are very difficult to spot... Because when reading the code, one often unconsciously considers these lines are correct...

Now people will ask that why in the world will someone create such a ridiculous blend of C and C++... The answer is... I don't know why... But anybody is absolutely free to mix the two compatible languages into a cocktail... I myself did this... when I was new into the dark realm of C/C++ programming... I had my own reasons... others will have their own...

note: *printf means any of the following funtion calls {printf, sprintf, fprintf}

Wednesday, March 4, 2009

Relevance of C/C++ in today's computing

A question mostly asked by fresh graduates is "C/C++ are still being used"? The answer is "Yes of course", C/C++ are still being widely used. Many open source projects are done using C/C++. Modern computing scene would be very different if C/C++ were not there... For example

1. Asterisk the open source PBX is written using plain old C language.
2. Maya, a top notch 3D animation suite is written using C++.
3. Postgres, leading open source DBMS which competes to Oracle is done using C.

C is considered the language of choice for writing Operating Systems. All Linux based operating systems are written using C. Microsoft Windows is written using C/C++. They (folks @ Redmond) tried to write Windows Vista using C#, but failed miserably.
C is known as "Mother of all programming languages". C/C++ are primarily used to write mission critical software, when we need high speed and smaller memory foot prints.I agree that we are living in an internet age, languages lis PHP/ASP.Net/Ruby on Rails are everywhere these days. But does anybody think, what is the engine powering these languages? The web-server which executes PHP code, the browser which displays CSS/HTML and dances around with AJAX, Adobe's Flash things, and many more are all done using C/C++.
Sometimes I think, I will do a detailed workshop titled "The Real Power of C/C++". I'm pretty ambitious in this regards, and I'll surely tell the world about "the happening"...

Thursday, February 19, 2009

Calling a web-method from a hyperlink

I've observed this trend in tech-industry, we will find many articles on difficult topics but its very difficult to find answers to simple questions.
I once faced such a question and figured it out after some experimenting.
The question is how to call a web method (a method exposed by a web service) from a plain HTML web page??? In other words how to call webmethods directly??? Well, folks its really simple to call a web-method from a hyperlink... The HTML goes like this...

<a href = "http://localhost/abcGateway/xgateway.asmx/dostartRecording?recchannel=19">
Start Recording

Where I have a web-service whose main page is xgateway.asmx, and it exposes a web method "dostartRecording", this web-method takes a parameter "recchannel".
 Hi ho now you can enjoy calling a web method directly from your web page.

Difference between Framework and API

Software Framework:

It is a re-usable design for a software system (or subsystem). A software framework may include programs, code libraries, a scripting language, other software to help develop and glue together the different components of a software project. Various parts of the framework maybe exposed through an API.
Microsoft's .Net framework is a very good example of a software framework. It contains compilers, class libraries, an IDE(Visual Studio), and a runtime. Another example is OpenCog: A Software Framework for Integrative Artificial General Intelligence.

API (Application Programming Interface):

It is a set of routines( AKA methods or functions), data structures, object classes, and/or protocols provided by libraries and/or operating system services in order to support the building of applications.
Good examples of API are Microsoft TAPI(Telephony API), or MySQL connectivity API, or Google MAPS API.

In Microsoft's .Net Framework, only the Base Class Library or BCL are the API. The framework is a bigger thing. API is a part, framework is a whole. Although, API can exist on its own, without a framework as well.
A friend was telling me yesterday "I interviewed someone, he had no idea about difference between Framework and an API". I replied"Owwww that's dumb". In fact, had no idea about the difference either.
Well, I think this much is enough to illustrate the difference between Software Framework and API, or Software Framework vs API.

Another example of software platform is pictured below, Google's Android Mobile Platform, 


You see this platform contains many things, a kernel for low level tasks, certain libraries for OS level chores, Delvik Virtual Machine (an enriched clone of Java Virtual Machine), and the "Application Framework" on on the "third story". Any software we write for Android smart phones will reside on 4th floor, which is labelled "Applications" here.
Some might search this topic as API vs framework, this blog entry will be equally helpful for those friends as well.

I'm working as a freelance programmer through ODesk.com, I have a strong profile over there. Feel free to ping me if you need an Android app.


Wednesday, February 18, 2009

Working with a std::vector inside an std::map

Suppose we have a map which contains std::string keys and std::vector values, it will be defined as following

std::map<std::string,std::vector> map_str_vector;

I was doing something like this:

std::vector vec_active_channels;
vec_active_channels.push_back("Some string");

map_str_vector["Some_Key"] = vec_active_channels;

Later in the code, I was erasing an element from the vector like this:

std::vector vec_temp = map_str_vector["Some_Key"];

But you know what, later on when I examined the vector, its size won't be changed.
The reason is when I did:
std::vector vec_temp = map_str_vector["Some_Key"];

A new object of std::vector was created and placed in vec_temp, and the call
was erasing first element from the new object.

The right way to remove a std::vector from a std::map value field is given below


We can put an if statement behind this erase operation, to check whether this key exists in the map or not.

C/C++ Common interview questions

Tech Interview C++

I got 2 years of experience and looking for a new job these days. I thought to write down the most commonly asked technical questions, they asked me.
  1. What is the difference between new/delete and malloc(), free()?
  2. What if we allocate memory using new and release it with free()?
  3. Why do we need virtual destructors?
  4. C++ compiler provides a copy costructor and overloaded assignment operator by default, why do we need to write our own copy constructors?
  5. Have you ever used STL, why do we use STL, if yes then what containers?
  6. What are function pointers?
  7. What happens when a callback funtion is called?
  8. Differences between C and C++?
  9. Write a program in C language which prints "Hello World!" on screen, without using even a single semi colon ';'.
  10. Swap two integers without using a third one.
  11. If we have a struct struct ABC{int n; char c;}; Suppose an integer takes 4 bytes. How many space in memory will be occupied by an instance of this structure?
  12. Why do we need pure virtual functions?
  13. What are friend functions?


  1. malloc() and free() are C language functions used to allocate and free memory. These funtions simply allocate memory for a variable. new/delete are C++ language operators, new operator allocates memory needed by an object and then calls the constructor function of that object to perform any initializations. Applying delete to an object causes a call to the destructor function of that object, and afterwards a release of memory. 
  2. The memory occupied by the object will be returned to Operating System, but the destructor of that object won't be called.
  3. Suppose you use delete with a base class pointer to a derived class object to destroy the derived-class object. If the base-class destructor is not virtual, then delete, like a normal member function, calls the destructor for the base class, not the destructor for the derived class. This will cause only the base part of the object to be destroyed.
  4. C++ default copy constructor and assignment operator perform a member to member copy of the instance variables contained by an object. If we have instance variables of pointer types in an object say object1, and we perform a straight member to member copy to object2. The pointer type instance variables in both object1 and object2 will be pointing to same memory locations. And if we delete one object, the pointers in other object will become invalid without that object ever knowing. This will cause a program crash.
  5. Standard Template Library is a standard peer revised and optimazed collection of containers and algorithms. Because it is standard, it is cross platform and any compiler supporting C++ standards must work with STL. Using STL cuts developement time, and increases program reliablity. I have personally  used vector, queue, and map containers.
  6. Callback funtions are also known as delegates. Callbacks are used when we want a method to be called from some other thread of execution. For example the boost::regex_grep function, its parameters are a large(or maybe small) string, a regular expression, and a call back funtion. The string can be very very long and finding the matches may take too much time, so whenever this boost::regex_grep funtion finds a match satisfying the supplied regular expression it will call the funtion in our code specified in callback argument.
  7. A callback funtion is basically a pointer to the starting location of some code, AKA funtion pointer. When a callback funciton is called, its parameters are pushed to stack. Then the control is transferred to the funtion pointer location and then the control resumes from the function pointer location.
  8. C is a functions based language, and it does not provide anything to group data with funtions which will manipulate that data. C++ is an Object Oriented language, and it provides rich constructs to group data with funtions which will manipulate it (AKA Data Encapsulation). It is possible to implement solutions close to real world using C++, by implementing heirarchical designs. C++ saves developement time by code resue through Inheritance as well.
  9. void main(void){if(printf("Hello World!")){}}
  10. int a = 10; int b = 20; a = a+b; b = a - b; a = a - b;
  11. An instance of this struct will take 8 bytes, because the C++ language compiler performs memory padding at every 4 bytes.It means, that a variable occupies at least 4 bytes in memory. 4 bytes is the basic unit of allocation in memory. This struct will take 4 + 1 = 5 bytes in memory, but the compiler will scale it up to 8 bytes by memory padding.
  12. If a class includes a pure virtual function, it can't be instantiated. A class which contains a pure virtual function is an abstract class. Abstract classes are also known as interfaces. In situations where we are defining interfaces, which will be used to contain pointers to child class objects only there must be some way to stop people from creating objects of these interfaces. Pure virtual functions server the purpose. Because an it compiler will stop us from creating an object of an Abstract class.
  13. Friend funtions are funtions which are not the members of a class, but can access the private members of an instance of that class.

A few unanswered questions as well, go figure!
1. Write a function such that if we input it 8, it returns 3 and if we input it 3 it returns 8. Don't use conditional statements.

2. Reverse a singly linked list in O(n) time and O(C) space complexity.

3. Find the third largest integer from an array, time constraints are O(n) and space complexity must be O(c).

4. INTERVIEW QUESTION: Malloc: Write an aligned malloc and free function that supports allocating memory such that the memory address returned is divisible by a specific power of two. CURRENT ANSWER: attached QUESTION FROM READER: I believe line 8 is wrong. It is assigning p2 equal to a (void **) and returning p2, but the function returns void *. I believe the corrected line should be p2[0] = (void * )(((size_t)(p1) + offset) & ~(alignment - 1)); line 10 should be return p2[0]; or could be return *p2;

I'm working as a freelance programmer through ODesk.com, I have a strong profile over there. Feel free to ping me if you need an Android app.


Friday, January 30, 2009

Passing NULL as output parameter

Although it seems okay, but its not okay to pass a variable initialized with NULL as out parameter to a function.

For example, I was doing this once upon a time
SomeClass *objSomeClass = NULL;
// where SomeFunction is supposed to return something in objSomeClass
// This code is correct by syntax, but created problems for me.

The right thing to do is

SomeClass * objSomeClass = new SomeClass();

cheers all...

More on TCP/IP streaming Sockets


I was writing server side code which will be reading commands from a client over a Win32 socket, problematic code was like this

// suppose m_sock is a working socket, all we gotta do is start receiving data on it

const int nBuffSize = 256;
int nRecv = 0;
char * szCmdBuff = new char [nBuffSize];
memset(szCmdBuff, 0, nBuffSize);
nRecv = recv(m_sock, szCmdBuff, nBuffSize, 0);
// do something with the data
memset(szCmdBuff, 0, nBuffSize);

Problem created by this code: Junk values in input.
Solution: do memset right before calling recv

Exact code to refresh things goes like this

memset(szCmdBuff, 0, nBuffSize);
nRecv = recv(m_sock, szCmdBuff, nBuffSize, 0);
// do something with the data
memset(szCmdBuff, 0, nBuffSize);

TCP IP sockets are the foundation rock of http protocol, which is the core of internet today. Having a solid understanding of how TCP/IP sockets work is essential to solve network communications problems.

cheers all...

Mistakes, not to be forgotten

Socket Programming:

Was writing a socket server few days back. The code was not working, it goes like(omitting error checks)

SOCKET g_sock_server;
g_sock_server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
bind(g_sock_server, (LPSOCKADDR) &g_addr_server, sizeof(g_addr_server));
listen(g_sock_server, SOMAXCONN);

SOCKADDR_IN addr_cli;
SOCKET s_cli;
int nSize = 0;
s_cli = accept(g_sock_server, (LPSOCKADDR)&addr_cli, &nSize);
if(s_cli == INVALID_SOCKET) return;
// rest of the code... say blah blah blah blah

The method accept will always return INVALID_SOCKET, guess why?

because of

int nSize = 0;

The fix is

int nSize = sizeof(addr_cli)

cheers all...