Endianness

July 12, 2008 by hnguyen2k

Big-Endian: MSB has the lowest address (Motoroal processors, SPARC)

Little-endian: LSB has the lowest address (x86, VAX, Z80, 6502)

+ Networks generally use big-endian order
+ English language uses big-endian order

Algorithms to determine the endianness of a machine:

//Return 0 if little-endian; 1 if big-endian
int Endianess1()
{
     int testNum = 1;
     char *ptr = (char*)&testNum;

return *ptr; //return the first byte
}

int Endianness2()
{
      union {
           int theInterger;
           char singleByte;
       } endianTest;

       endianTest.theInteger = 1;
       return endianTest.singleByte;
}

C++’s Memory Areas

June 30, 2008 by hnguyen2k

The following table summarizes a C++ program’s major distinct memory areas. Note that some of the names (for example, “heap”) do not appear as such in the standard; in particular, “heap” and “free store” are common and convenient shorthands for distinguishing between two kinds of dynamically allocated memory.

Table 1. C++’s Memory Areas
Memory Area Characteristics and Object Lifetimes
Const Data The const data area stores string literals and other data whose values are known at compile-time. No objects of class type can exist in this area. All data in this area is available during the entire lifetime of the program. Further, all this data is read-only, and the results of trying to modify it are undefined. This is in part because even the underlying storage format is subject to arbitrary optimization by the implementation. For example, a particular compiler may choose to store string literals in overlapping objects as an optional optimization.
Stack The stack stores automatic variables. Objects are constructed immediately at the point of definition and destroyed immediately at the end of the same scope, so there is no opportunity for programmers to directly manipulate allocated but uninitialized stack space (barring willful tampering using explicit destructors and placement new). Stack memory allocation is typically much faster than for dynamic storage (heap or free store) because each stack memory allocation involves only a stack pointer increment rather than more-complex management.
Free Store The free store is one of the two dynamic memory areas allocated/freed by new/delete. Object lifetime can be less than the time the storage is allocated. That is, free store objects can have memory allocated, without being immediately initialized, and they can be destroyed, without the memory being immediately deallocated. During the period when the storage is allocated but outside the object’s lifetime, the storage may be accessed and manipulated through a void*, but none of the proto-object’s nonstatic members or member functions may be accessed, have their addresses taken, or be otherwise manipulated.
Heap The heap is the other dynamic memory area allocated/freed by malloc()/free() and their variants.

Note that while the default global operators new and delete might be implemented in terms of malloc() and free() by a particular compiler, the heap is not the same as free store, and memory allocated in one area cannot be safely deallocated in the other.

Memory allocated from the heap can be used for objects of class type by placement new construction and explicit destruction. If so used, the notes about free store object lifetime apply similarly here.

Global/Static Global or static variables and objects have their storage allocated at program startup, but may not be initialized until after the program has begun executing. For instance, a static variable in a function is initialized only the first time program execution passes through its definition. The order of initialization of global variables across translation units is not defined, and special care is needed to manage dependencies between global objects (including class statics). As always, uninitialized proto-objects’ storage may be accessed and manipulated through a void*, but no nonstatic members or member functions may be used or referenced outside the object’s actual lifetime.

 

It’s important to distinguish between the “heap” and the “free store,” because the standard deliberately leaves unspecified the question of whether these two areas are related. For example, when memory is deallocated via ::operator delete(), the final note in section 18.4.1.1 of the C++ standard states:

“It is unspecified under what conditions part or all of such reclaimed storage is allocated by a subsequent call to operator new or any of calloc, malloc, or realloc, declared in <cstdlib>.”

UTF–8 and Extended characters

June 12, 2008 by hnguyen2k

Character Range (hex)

 

Unicode (UCS-2/UTF-16)

UTF-8

0-7F

00000000 0xxxxxxx

0xxxxxxx

80-7FF

00000xxx xxxxxxxx

110xxxxx 10xxxxxx

800-FFFF

xxxxxxxx xxxxxxxx

1110xxxx 10xxxxxx 10xxxxxx

10000-1FFFFF

- out of range -

11110xxx 10xxxxxx 10xxxxxx
10xxxxxx

200000-3FFFFFF

- out of range -

111110xx 10xxxxxx 10xxxxxx
10xxxxxx 10xxxxxx

4000000-7FFFFFFF

- out of range -

1111110x 10xxxxxx 10xxxxxx
10xxxxxx 10xxxxxx 10xxxxxx

Note that all bytes of multi-byte UTF-8 characters have the high-bit set to one, and only the first byte of a multi-byte character has both its highest bits set. This means there can never be confusion about where a character starts. So in UTF-8, the combined Greek and Latin sequence aβcδe is represented by the following seven bytes, and looking at the high bits you can pick out the extended characters without too much trouble:

01100001 11001110 10110010 01100011 11001110 10110100 01100101

Now the really clever bit about UTF-8 is that it is capable of passing unharmed through ASCII only systems [programs which don’t even recognize UTF-8], thanks to the fact that each character beyond U+007F looks like a valid sequence of extended ASCII when read as a byte-per-character. This is in stark contrast to other Unicode encodings such as UCS-2, which are full of zero bytes and therefore wreak havoc with ASCII processing systems. To an ASCII system, the UTF-8 representation of aβcδe parses as aβcδe . On the surface this may seem like a corruption, but the important thing to note is that no illegal ASCII characters appear in a UTF-8 bytestream, and so the same string can be read and written out again as raw ASCII and then decoded later as the original UTF-8. With the exception of 7-bit text systems [a legacy email standard, unfortunately, for which the hideous UTF-7 had to be invented] UTF-8 should be able to pass through ASCII systems unscathed.

 

Exception safety

June 9, 2008 by hnguyen2k

Never allow an exception to escape from a destructor or from an overloaded operator delete() or operator delete[](); write every destructor and deallocation as though it had an exception specification of “throw()”

In each function, take all the code that might emit an exception and do all the work safely off to the side. Only then, when you know that the real work has succeeded, should you modifiy the program state (and clean up) using only non-throwing operations.

The Pleasure of Reading

May 19, 2008 by hnguyen2k

    Animals may have moments of pleasure but only man has got a lot to do with it. It is through our sense of organs that we enjoy pleasure. The sense of smell, sight, hearing, touch and taste each brings pleasure. Even the baby as soon as it is born feels the pleasure of suckling and the comfort of being cuddled in the wads of cloth in the mother’s lap. But for the pleasing smell we will not be able to enjoy our food. We are thrilled by the sight of ice capped mountains or the roaring water falls of the Niagara. So they are the sense that help us to get the pleasure. 

    There is no end to the sources of pleasure. But reading for pleasure belongs to a higher order and stands as a category by itself. While external things bring pleasure to the sense organs, reading brings pleasure to the mind. Greater the mind is cultured, greater will be the pleasure derived from reading for reading makes full man.

    Reading is the end product of writing. Unless there is something written one cannot read. So good writing is a concomitant of reading. Man alone can write, in other words put his ideas in black and white. In fact even before printing came into being man was writing and it is as old as modern civilization. Man can preserve his thoughts and ideas through writing. Thus the whole world of literature is there for one to read.

   Now reading material is available for all tastes. A scholar may go through serious writing for the sake of enriching his knowledge. Another may read a magazine or a picture book for whiling away the time. One chooses the reading material according to his moods, his literary background, the time at his disposal and ther purpose if any. A teenager may like stories of romance and an old man may prefer books on philosophy and religion. Some gifted with imagination and the faculty to reflect may read poetry.

   One who takes pleasure in reading always tries to build his library. Very often a good library may serve the purpose.

   The greatest advantage in reading is when one comes across great minds. Whether you agree with what is there to  read or do not agree there will not be any quarrel. You may pronounce your judgement on the writer. There will be no harm if your judgment is silent and not published.

   Given the proper atmosphere like a good silent place, soft light and comfortable seat, one can read and read and enjoy it.

   There are greate master of writing in all great languages of the world. English language abounds in such great authors. Again it may be poetry, novel, fiction, drama, travelogue, letters and so on. Biographies and autobiographies form a sizable part. In these days of rush good magazines supply the material for reading. For example , one may cite the Reader’s Digest.

   In order to enjoy reading, one must cultivate that habit. It can be ennobling. There is dignity in the reading habit.

C++: RAII with auto_ptr and shared_ptr

May 16, 2008 by hnguyen2k

RAII: Resource Aquisition Is Initialization - The technique combines acquisition and release of resources with initialization and uninitialization of objects.

auto_ptr: is a pointer-like object (a smart pointer), whose destructor automatically calls delete on what it points to. It’s important that there never be more than one aut_ptr pointing to an object because an auto_ptr automatically delete what it points to when the auto_ptr is destroyed.
      std::auto_ptr<Student>p1(new Student);    //p1 points to an Student object
      std::auto_ptr<Student>p2(p1);                  //p2 now points to the obj, p1 is now null
      p1 = p2                                                       //p1 now points to the obj, p2 is null

shared_ptr: is a reference-counting smart pointer that keeps tracks of how many objects point to a particular resource and automatically deletes the resource when nobody is pointing to it any longer. (Like a garbage collection except that such pointers can’t break cycles of references, e.i two otherwise unused objects that point to one another)
     std::tr1::shared_ptr<Student>p1(new Student);  //p1 points to a Student object
     std::tr1::shared_ptr<Student>p2(p1);                //both p1 and p2 point to the object
     p1 = p2;                                                            //same

Both auto_ptr and tr1::shared_ptr use delete in their destructors, not delete[]. Therefore, they should not be used with dynamically allocated arrays:
    std::auto_ptr<std::string> aps(new std::string[10]);  //bad
    std::tr1::shared_ptr<int>spi(new int[1024]);             //bad  

C++ placement new

May 15, 2008 by hnguyen2k

Operator new allocates memory from the heap, on which an object is constructed. Standard C++ also supports placement new operator, which constructs an object on a pre-allocated buffer. This is useful when building a memory pool, a garbage collector or simply when performance and exception safety are paramount (there’s no danger of allocation failure since the memory has already been allocated, and constructing an object on a pre-allocated buffer takes less time):

char *buf = new char[1000]; //pre-allocated buffer
string *p = new (buf) string(”hi”); //placement new
string *q = new string(”hi”); //ordinary heap allocation

C++ new cast forms

May 13, 2008 by hnguyen2k

C++ offers four new cast forms (often called new-style or C++ style casts)

1. const_cast<T>(expr): used to case away the constness of objects. It is the only C++ style cast than can do this.

2. dynamic_cast<T>(expr): used to perform “safe downcasting”, i.e., to determine whether an object is of a particular type in an inheritance hierarchy. It is the only cast that cannot be performed using the old-style syntax. It is also the only case that may have a significant runtime cost.

3. reinterpret_cast<T>(expr): used for low-level casts that yield implementation-dependent (i.e unportable) results, e.g., casting a pointer to an int. Such casts should be rare outside love-level code.

4. static_cast<T>(expr): used to force implicit conversions (e.g. non-const object to const object, int to double, etc). It can also be used to perform the reverse of many such conversions (e.g. void* pointers to typed pointers, pointer-to-base to pointer-derived), though it cannot cast from const to non-const objects. (Only const_cast can do that)

Prefer C++ style casts to old-style casts because they are easier to see, and they are more specific about what they do

C/C++ Const-ness

May 13, 2008 by hnguyen2k

const char* : non-const pointer to a const value
char const*: same as const char*
char* const: const pointer to a non-const value
const char* const: const pointer to a const value

How to ensure road safety

May 13, 2008 by hnguyen2k

    Why think of road safety at all? It is because of the accidents that occur everyday on the road, in which all sorts of vehicles and human beings and even animals are involved. These accidents mean loss of life and loss of property and more often than not obstruction to traffic. In this age of speed and fast moving vehicles and with the congestion on roads, these accidents have become almost an everyday affair. So unless everybody is educated on the importance of road safety, the loss and the sorry spectacles cannot be avoided.

    Prevention is better than cure. This holds good even in the matter of road accidents. Accidents are due to many causes and may occur under different circumstances. The simplest but at the same time dangerous perhaps is people slipping down on the road caused by an orange or a banana peel. Without meaning any harm, quite innocently a person may throw away the orange peel or the banana skin on the road or the side walk. When a fast walking person steps on it he or she slips down ending a fracture of bones and sometimes more dangerous than that. So people must take care they do not throw the peelings on the road but should deposit them in a dust bin. In some countries the offenders are severely punished. 

   The second cause of accident is due to careless crossing in busy roads. While crossing one must look to the right and left for moving vehicles and then cross. (Where there are Zebra markings on the road for the pedestrians to cross, one shoud cross along them. One should keep the margin of the road while walking and the vehicles must keep to their lanes in busy streets.

    In the case of accidents involving vehicles these are many causes. One is trying to overtake and very often taking risk. Another has wrong judgement in crossing. Sometimes it may be not caring for the signals. In crowded streets. “Stop, look and go” is the best precept; it will save vehicles from accidents. But where one takes a foolish step, the result is the inevitable accident. Jay riding may be another cause. Riding two or three abreast is always dangerous. Especially one must be aware of this. Scooter riders become victims of road accidents. But if they just wear the helmet as required by law, they could easily avoid fracture and hence death. 

   Very often the cause of accidents is the failure of the brake system which means the owner of the vehicle does not care to keep the machine in good condition. By attending to the vehicle regularly a lot of miseries could be avoided.

   Road safety is a matter of education in which the school can play a significant role. Through scouting, Red Cross and social education classes, children can be taught the importance of observing the rules of the road. Children must be taught their limbs and lives are very valuable and they must not take risk, especially when leaving the school. As soon as the bell goes, children rush out and accidents do happen. Under the circumstances the teachers must feel it their duty to regulate the traffic near the school. The police can cooperate with the school in this respect.

   To make the people road conscious, the mass media can be used. The newspaper, the wall poster and cinema and now the TV come in handy. Shots in the cinema or TV emphasizing the importance of road safety can be highlighted. There may be speeches over the radio by the police official. During peak hours in crowded areas, the police may direct the traffic and ask people to keep to their lanes.

——

(From 556 New Best Essay & Writings)