C++ references, because pointers are overrated

I read some day in some C++ book a quote: “References are the sweets of C++”. I can almost swear that this quote belongs to Bjarne Stroustrup as my weak memory remembers, but I have no evidence. This quote is the motivation behind this blog post.


  • Shed the light on C++ references beauty
  • Suggest a Do/Don’t guidelines and good practices for using references
  • Indirectly begging you not to use pointers everywhere to look geek


  • Another cplusplus.com tutorial on references or pointers
  • Another stackoverflow question in the regex form of: * Pointers * References *?
  • Illustrate how dumb is writing using namespace in header files


[o] References and Pointers have exact dereference and member function call assembly

In case you thought that one has performance advantage over the other, they only differ in semantics

    int x = 10;
00D453E8  mov         dword ptr [x],0Ah  
    int& xRef = x;
00D453EF  lea         eax,[x]  
00D453F2  mov         dword ptr [xRef],eax  
    int* xPtr = &x;
00D453F5  lea         eax,[x]  
00D453F8  mov         dword ptr [xPtr],eax  

    xRef = 20;
00D453FB  mov         eax,dword ptr [xRef]  
00D453FE  mov         dword ptr [eax],14h  
    *xPtr = 30;
00D45404  mov         eax,dword ptr [xPtr]  
00D45407  mov         dword ptr [eax],1Eh  
    Foo foo;
    Foo& fooRef = foo;
009E50BD  lea         eax,[foo]  
009E50C0  mov         dword ptr [fooRef],eax  
    Foo* fooPtr = &foo;
009E50C3  lea         eax,[foo]  
009E50C6  mov         dword ptr [fooPtr],eax  

009E50C9  mov         ecx,dword ptr [fooRef]  
009E50CC  call        Foo::Bar (09E1429h)  
009E50D1  mov         ecx,dword ptr [fooPtr]  
009E50D4  call        Foo::Bar (09E1429h)  

[o] Pointers inheritance/polymorphism rules apply

class A { public: void Foo() { /* Do A Stuff */ } };  
class B : public class A { public: void Foo() { A::Foo(); /* Do B Stuff */ } };  
B b;  
A& a = b; // Reference acts like a pointer  
a.Foo(); // B::Foo will be called which will call A::Foo


[v] Pass Out and In/Out parameters by reference and In parameters by const reference

A pass by non-const reference is a contract between the caller and callee that a parameter is either write (Out) or read/write (In/Out), to distinguish between them in Visual Studio use the SAL annotation _Inout_. More on SAL here. On the other hand, a pass by const reference is a contract between the caller and callee that a parameter is read-only (In), and you don’t need SAL to specify that, it is implicit.

[v] Hold STL containers indexing\accessor return by reference

For C++11, auto& will always work for STL containers unless you intentionally need to work with a copy

// Assume: vector< vector<Tile> > grid;
// This is a bad design for a matrix grid
for (size_t y = 0; y < grid.size(); ++y)
	for (size_t x = 0; x < grid[y].size(); ++x)
		Tile& tile0 = grid[y][x];
		// Or the C++11 way
		auto& tile1 = grid[y][x];
		// This is a tile copy
		auto tile2 = gird[y][x];

		A chunk of code operating on tile
		No need to spam writing grid[y][x] everywhere,
		indexing is cheap but it may not be for map or set

[v] Use auto& to avoid unintended value copy (C++11)

auto is a bit tricky, you think it is smart enough to understand that you want your type by reference, but it isn’t

One example is the std::map indexing operator [], its return type is a reference to a value type

// Assuming an empty std::map<string, Member> accounts
// s is a value copy of Member
auto s = students["KokoElDa3ef"];
// Chang the s copy of the original member record
s.email = "koko@wawa.com";
// Outputs nothing
cout << students["KokoElDa3ef"].email;

// s is a reference to a Member
auto& s = students["KokoElDa3ef"];
// Chang the original member record
s.email = "koko@wawa.com";
// Outputs koko@wawa.com
cout << students["KokoElDa3ef"].email;

// Assuming: std::map<int, Actor> sceneActors;

// actor is a reference type
for (auto& actor : sceneActors)
{ /* something goes here */ }

// actor is a value type, and is a shallow copy of 
// the actual Actor stored in sceneActors map
for (auto actor : sceneActors)
{ /* something goes here */ }

[v] Use pointer parameters when null is expected and legal

void Foo(Bar* barPtr)
	// This is dangerous, it assumes that you will always
	// get a non null barPtr, be defensive with if (nullptr == barPtr) return;

void Foo(_In_opt_ Bar* barPtr)
	// _In_opt_ says that the pointer can be null
	// it is unsafe to use it without validation, but
	// at least the contract is clearer with SAL
	// Use _In_ if you have a guarantee that barPtr
	// will always be valid (the caller guarantees that)
	// You can't always guarantee the caller, thats why
	// a defensive if/return is a must especially if you are
	// writing an API that will be used by a 3rd party code
	// Use reference to make it clear without SAL

void Foo(Bar& barRef)
	// You can access bar instance safely. 
	// The referance contract says that it won't be null
	// If bar was a pointer, you would guard yourself with
	// If (barPtr != nullptr) return;
	// Using SAL with references is still good and makes
	// your code ultimately clear

[v] Use reference to an object for a cleaner operator call syntax

// Assume a 2D dynamic matrix pointer vector< vector<int> >* matrixPtr
// some 2 for loops i,j operating on m(i,j) using indexing operator
int cell = matrixPtr->operator[](i)->operator[](j);

// Assume a 2D dynamic matrix reference vector< vector<int> >& matrixRef
// some 2 for loops i,j operating on m(i,j) using indexing operator
int cell = matrixRef[i][j];

[v] Capture by reference [&var] () {} for lambda closures when a reference makes sense (C++11)

Unless you really want your closure to have a copy of one of its non basic type captures, capture by reference, especially if they are will be used as read-only

string str = "Hello World";
auto displayStr = [&str] () { /* something goes here with str */ }

[v] Return ready-only class property by reference/const reference to specify object ownership

I consider this point as the most important of all them all. Unless Null is allowed for a class property return value, return property value by reference/const reference to specify that the an object owns what is returned from this property in terms of memory management AND that returned value (either it is another object or a simple type) is as alive as the owning object is alive and dies when the owning object dies. This practice will make your native programs less prone to memory leaks and make your life easier. Examples will make the concept more clear

// Assuming that Mat4x4 is a 16 float sized object
class GameObject
	// Bad: does not add any value, const ref is the way to go
	Mat4x4 Transform1() const { return m_transform; }

	// Bad for read/write transform (Can I get a nullptr matrix? Can I delete it?)
	Mat4x4* Transform2() { return &m_transform; }

	// Bad for read-only transform (Can I get a nullptr matrix?)
	const Mat4x4* Transform3()  const { return &m_transform; }

	// Good for read/write transform
	Mat4x4& Transform4() { return m_transform; }

	// Good for read-only transform
	const Mat4x4& Transform5() const { return m_transform; }

	// Can I get the RigidBody pointer and delete it and let you crash and burn?
	PhysicsRigidBody* RigidBody1() { return m_&pRigidBody; }

	// You can get the RigidBody read it, but you can't delete it
	const PhysicsRigidBody* RigidBody2() const { return& m_pRigidBody; }

	// Bad: Will you crash if m_pRigidBody is nullptr?
	// Can I hold a reference onto it for a while? Will it stay valid?
	const PhysicsRigidBody& RigidBody3() const { return *m_pRigidBody; }

	// Kinda Good: You can get around the nullptr problem by using
	// the Null Object design pattern
	const PhysicsRigidBody& RigidBody4() const
		if (nullptr == m_pRigidBody)
			return PhysicsRigidBody::Null();
		return *m_pRigidBody;
	Mat4x4 m_transform;
	PhysicsRigidBody *m_pRigidBody;


[x] Use const reference for In parameters of basic types

Most basic types have size <= size of a pointer (i.e sizeof(void*) or sizeof(size_t)) (e.g char, short, int, unsigned char, unsigned short, etc ..)

[x] Pass read-only basic type parameters by reference

It makes sense to pass a parameter by const reference if its type size is > pointer size. Why? Observe the assembly and judge

void Foo(char c)
// Omitted assembly goes here
    char a = c;
002E394E  mov         al,byte ptr [c]  
002E3951  mov         byte ptr [a],al   

void Tar(const char*c)
// Omitted assembly goes here
    char a = *c;
002E3A0E  mov         eax,dword ptr [c]  
002E3A11  mov         cl,byte ptr [eax]  
002E3A13  mov         byte ptr [a],cl 

void Bar(const char& c) 
// Omitted assembly goes here
    char a = c;
002E2C3E  mov         eax,dword ptr [c]  
002E2C41  mov         cl,byte ptr [eax]  
002E2C43  mov         byte ptr [a],cl  


  • Consider passing by reference as your default choice unless:
    • A NULL object/value is a valid case for which you pass by pointer
    • sizeof(Type) sizeof(void*) pass by const reference. You can safely pass most basic types by value without worrying about a performance hit.
    • A parameter is meant to be copied for which you pass by value
  • Consider using SAL annotations to help clarify your contracts even if you are not willing to run VisualStudio static code analysis

*Please notify me if you find any mistake. Your feedback is very welcomed.

Unusual C++ use of #include

Wanted to share with you an unusual way of using the very well-known #include C++ preprocessor directive.

"The #include directive causes a copy of a specified file to be included in place of the directive" – C++ How To Program

The usual use is to write it at the very top of your .h/.cpp files to include other header files like (Windows.h, iostream, cstdio, etc..) to use the what is defined inside in your .h/.cpp file.

The unusual use is to use it to initialize a data-structure like arrays by including a text file that contains the array initialization data between the array initializer list parentheses – e.g XX XXX[] = { <HERE> }. This is is illustrated in the sample program below. The same concept can be used to initialize an array of any dimension.

A Simple Sample

// main.cpp
#include <cstdio>
#include <Windows.h>

struct Person
    char        *pName;
    unsigned    Age;
    unsigned    Height;
    char        Gender;

// Declare and initialize a 1D array of Persons structs using PersonTableData text file
// #include "PersonsTableData" will be expanded at COMPILE TIME to the content of PersonsTableData file
Person PersonsTable[] = {
    #include "PersonsTableData"

int main()
    for (int i = 0; i < _countof(PersonsTable); ++i)
        Person &person = PersonsTable[i];

        printf("%s\t%d\t%d\t%c\n", person.pName, person.Age, person.Height, person.Gender);

    return 0;


PersonsTableData text file content










It is not about how many programming constructs you memorize of your preferred programming language, it is about how can you utilize the constructs you know for your own good.

SDET Daily’s::Backtracking Part 2::My Microsoft Interviews

I’d like to dedicate this post to talk about my Microsoft interviews. I`ve learnt a lot from it, and I will list some of what I learnt  through the post.

Before I begin, I’d like to write my definition for Interviews trials, especially for fresh-graduates:

Interviews trials are like a chain of failures, that ends with a success link.

The most thing I don’t like is …

كفاية عنجليزي, حبة عربي بقي, تحيا مصر يا عم


التجربة الأولي في بلاد الأتراك

الرحلة بدأت في سنة رابعة, قدمت في الترم الأول و عملت فون إنترفيو  إتش أر و قالولي إنت عديت و هتنتقل للمرحلة اللي بعديها و بعديها بشوية عقبال ما عطفوا عليا الترم التاني قالولي هتسافر تركيا تعمل الإنترفيوهات عشان مش هينفع في مصر عشان أياميها كان فيه قلق و مظارهات بتاعة الثورة و كانوا خايفين ينزلوا مصر

سافرت تركيا و كانت فسحة كميلة جدا, الواحد كان مفحوت في وسط المشاريع و خصوصا مشروع التخرج و شغل الإي سي إم و كانت فرصة الواحد يغير جو, ميكروسوفت تقولك إنت هتسافر بلد معينه عشان تعمل إنترفيو إعرف إن الست الوالدة دعيالك بضمير, لأنك هتتفسح ببلاش, طيارة, فندق, أكل, تاكسيهات و غيره, كل ده علي حساب ميكروسوفت, يعني إنت رايح باشا, تقول الكلمتين اللي عندك و ترجع بيتكم تاني تكمل اللي كنت بتعمله. مؤخرا ميكروسوفت كانت بتسفر دبي و تركيا و المكانين أنضف من بعض

المهم إن التيم اللي كان بيعمل إنترفيوهات هو تيم الأوفس, طبعا هموا كانوا فاحتيننا أسئلة في ال تيستينج, خصوصا التست اللي من النوع اليدوي, اللي هو تتأكد إن البرنامج اللي قدامك ده شغال كويس إذاي و مفهوش أخطاء, من غير ماتكتب كود, و صراحة دي حاجة فصلتني شوية, بس عادي المفروض كنت أجاوب كويس في أي حاجة, و أرجع و أقول

المبرمج الصح هو اللي يعرف يهري في أي جوافة 

إتسألت سؤالين تيستنج و 3 أسئلة إكتب كود و إعمله تست, و أكتر انترفيو فيهم معلمه معايا اللي الراجل فتح قدامي لابتوب عليه و يندوز 7 و قالي أتست إن حاجة معينه شغاله و عايز يعرف أعملها تست إذاي, الفكرة إني كنت أول مرة أشوف ويندوز 7 في حياتي و مكنتش منزله عندي علي الجهاز و لا جربته, فاللي هو شعور: أنا سعيد إنك سألت السؤال ده, طبعا الراجل إتقفل مني لأني قعدت أهري كتير و موصلتش لحاجة, لأني مش فاهم هو عايز إيه, و ده أول حاجة إتعلمتها

متجاوبش علي سؤال غير لما تتأكد إنك فاهمه كويس, و مش عيب تسأل و إعمل هندي

المهم إنك تجاوب علي السؤال بطريقة كويسة لأن ردك الكويس هو اللي هيغفرلك الإنجليزي الواقع بتاعك و هيخلي الإنترفيور يعديهالك, و حتي لو عكيت, قدام فرصةتعوض في الإنترفيو اللي بعديها, و عشان كده بيدوك مثلا فرصة كذا إنترفيو ورا بعض عشان لو عكيت في واحدة تعوض في الباقي, أنا اللي فاكره من الأسئلة الأتي

  • 1st Problem: Find the duplicate number in a sorted array of size N where only one number is duplicate. The numbers will be in the range 0 to N-1 inclusive
  • Input 1: 1 2 3 4 5 6 6 7 8
  • Output 1: 6
  • Input 2: 1 1 3 4 5 6 7 8 9
  • Output 2: 1
  • I wrote the O(N) which uses the sequence sum mathematical formula,  and the interviewer asked me to get a O(log N) solution, I figured one that uses the binary search and I was asked to test my O(log N) solution extensively.
  • 2nd Problem: Convert a binary search tree to a doubly circular linked-list by setting the Next, Prev pointer fields of the Node struct of each tree node.
  • 3rd Problem: It was somehow complex, and It was related to a problem in MS Word application – remember that I was being interviewed with MS Office team -, in the text Encoding detection module, and I was asked to write something in which I deal with a byte buffer, and I had to deal with these bytes and make some dirty bit-masking work to detect some patterns.
  • 4th Problem: Test the Font dialog in the Notepad.exe application.
  • 5th Problem: Test the Screen Lock feature of MS Windows 7 (the one with “Press Alt+Ctrl+Delete to log in).

جاوبت علي قد ما أقدر, بس إترفضت و أنا كنت حاسس, بس الجميل إني لما سألت الريكروتر إيه المشكلة اللي عندي, قالتلي مش هينفع أقولك, دي بولسي في ميكروسوفت,  سابتني كده, مفرقتش معايا كتير لأني كنت حاسس إيه اللي عكيت فيه

و طبعا إترفضت, و أنا مكنتش زعلان لأن مستوايا مكنتش راضي عنه, و عكيت شوية, و مكنتش فت نت, خيرها في غيرها

مشاكل التجربة التركية

المشاكل اللي كانت عندي في التجربة دي تتلخص في إني كنت بتسرع في الإجابة قبل ما أتأكد إني فاهم السؤال كويس, و إني مكنتش كفاءة في إني أحل مسائلة برمجة معقدة علي السبورة و أنا وقافع لأني متعود علي الفيجوال ستوديو أو علي ورق و أنا قاعد براحتي و كنت بتلخم ساعات

خلصنا من تركيا و رجعت مصر, و الحياة مشيت عادي لأني كنت رايح أغير جو و بهدف إني أجرب نفسي, و نصيحتي للشبباب اللي في الكلية و لسه في سنة تالتة و رابعة, إستغل الفترة دي في إنك تاخد الخبرة اللي ملهاش علاقة بالبرمجة علي قدر ما تقدر, خبرة التقديم و إذاي تتكلم عن نفسك و إذاي تتحاور مع اللي قدامك و كل ده ملوش علاقة بالبرمجة و كده كده لسه الفرصة قدامك, لو إترفضت مش هتتكدر ذي واحد خريج بقاله سنة بيحاول يدور علي شغل و إترفض مرتين تلاتة قبل كده

    التجربة التانية في شرم الشيخ

    بعد ما اتخرجت قدمت تاني, و المرة دي عملت إتش أر فون انترفيو و كالعادة الكام سؤال المحفوظين بتوع الإتش أر, الحمد لله عديت و بعد كده قالولي هتعمل تيكنكال انترفيو في فندق ماريوط الزمالك, و دي كانت في الحارة المزنوقة ذي ما بيقولوا, لأننا كنا بنعمل إنترفيو في الأوضة بتاعة كل إنترفيور, ميكروسوفت كانت معفنة في الحركة دي, بس عديها

    عملت إتنين إنترفيو في ماريوط واحدة إتش أر و واحدة تيكنكال و عديت منهم الحمد لله و اللي فاكره إني إتسألت سؤال واحد تيكنيكال و كان سؤال تقليدي

  • Problem: Write a function that reverses a sentence in-place
  • Input: Hello World I am EPIC
  • Output: EPIC am I World Hello

    عديت منها الحمد لله و بعديها قالولي إنت هتسافر شرم الشيخ الفينال راوند, طبعا الطيارة و الفندق و الحركات دي كلها علي حساب ميكروسوفت. بدأت أستعد عشان مضيعش مني الفرصة دي, أنا كنت عايز أحل مشكلتي إني أحل مسأله بسرعة علي ورق و تكون صح من أول مرة, طبعا الموضوع ده سهل لو إنت بتدرب علي توب كودر أو يو في إيه, بس مكنش فيه وقت بالنسبة لي و كنت مشغول بحاجات تانية الفترة دي, فقرر أجمع أسئلة برمجة كتير و أقعد أحلهم علي ورق كذا مرة عشان أمشي إيدي علي الورق, و أعود نفسي أعمل تريس علي ورق – تحس إن لسه متعلم برمجة إمبارح –. بالإضافة لكده قريت كتاب

    Programming Interviews Exposed: Secrets to Landing Your Next Job, Second Edition

    و حليت كل المسائل اللي فيه الحمد لله, الكتاب مفيد جدا و أنصح بيه أي حد مش هيندم, ممكن تلاقي كلام إنته عارفه قبل كده, بس في العموم هتستفاد.

    إتعودت إن عندي فولدر كده فيه كل الإستعدادات لأي إنترفيو, مجمع فيه الحاجاتي اللي منها أراجع و أسترجع معظم الحاجات الواقعة, في أخر البوست هحط لينك عليه الفولدر ده عشان الفايدة تعم برضه

    المرة دي أنا راح الإنترفيو و أنا واحد مختلف تماما عن البني أدم اللي عمل إنترفيو في تركيا. ليه؟ ليــه؟ ليــــــه؟ قولتلي ليه, جميل, أقولك أنا

    في الفترة دي كنت شغال في شركة إن تي بي سوفتوير, و كنت بقالي بتاع 3 شهور شغال يعني كنت بدأت أفهم أنا شغال في إيه, و دي فرصة إني الاقي حاجة كبيرة أتكلم عليها بجانب مشاريع الكلية, و في نفس الوقت جنب الشغل كنت بقرا كتاب

    Windows via C and C++, Fifth Edition

    الكتاب ده بيتكلم عن حاجات فضائية في الويندوز ذي

    User/Kernel Objects, Process and Threads, Thread Synchronization Techniques, Windows Memory Architecture including dealing with Virtual Memory in details, DLLs and DLL Injection Techniques (Was the most OMG part for me), Windows Structured Exception Handling, etc..

    الكتاب ده غير مفهومي عن البرمجة, لأول مرة بقيت فاهم البرنامج اللي أنا بكتبه الويندوز بيشغله إذاي لمستوي من التفاصيل أنا مكنتش أتخيله, الكتاب ده أنا بعتبره الزتونة للويندوز بروجرامنج – أنا قفلت من كلمة “بروجرامنج” و أنا بكتبها, أنا أسف, نصيحة لأي شاب جييك ليه في قلة الأدب و السفالة في البروجرامنج إنه يتجه علي الكتاب ده و هيدعيلي كتير

    التالي هو سرد لل 5 إنترفيوهات اللي عملتها حسب ما أنا متذكر

    First Interview:

  • Talk about a project you are proud of, what have you learnt and problems faced you
  • A developer in the company wrote a SHUFFLE function that shuffles an array of integers, and we don’t have access to its source code, implement a function with the following definition bool TEST_SHUFFLE(int inArray[], int outArray[]); to test the SHUFFLE function which returns TRUE if outArray is a real shuffle of inArray, and FALSE otherwise. The inArray is the original array provided to the SHUFFLE function and outArray is the output of the SHUFFLE function.

    Second Interview:

  • Discussion about my graduation project and artificial intelligence
  • Design and Implement a string class to be used by Microsoft developers Third Interview:
  • Discussion about a certain project I have been interested in
  • Write a pseudo-code of a Driver for hard-disk that acts as a request dispatcher, the driver should accepts I/O requests from the file system and dispatch them to the hard disk, the hard disk receives I/O requests on 4 registers (R1, R2, R3 and R4), and is able to process 4 requests only at a time, the sequence that the hard-disk process the requests is not depending on the sequence of adding the requests in the registers, and it’s the hard-disk job to optimize the order of requests processing.
  • The hard-disk will fire a software interrupt (callback) to the driver indicating the completion of one of the requests place in one of its 4 registers.


    Fourth Interview:

  • You are a member of the CLR team and you want to decide the triggers that fires the garbage collector, i.e the events on which the CLR engine asks the garbage collector to work. Fifth Interview:
  • You are to write the program for a land telephone that accepts a string of characters and convert them to the corresponding numbers

    الحمد لله مستوايا كان أفضل بكتير من أول مرة, لكن في نفس الوقت مكنتش راضي عن نفسي 100% بس كنت حاسس إني أديت كويس في العام و كنت متوقع إني بنسبة كبيرة إتقبلت و هيدوني أوفر لأن كذا إنترفيور كانوا مبسوطين حسب ما كان واضحلي و أنا كنت بجاوب كويس إلي حد ما, بس في وسط كل ده أنا عارف أنا عكيت في إيه و إيه الحاجات اللي عايزة تتظبط, و عارف إني لو متقبلتش إيه الحاجة المؤثرة اللي وقعتني, و دي أهم ملكة في كل الليلة دي, إن الواحد يعرف يحس بنفسه, و دي بتبقي نعمة و فضل من ربنا علي الواحد. إترفضت برضه مرضيوش يقولولي إيه المشكلة اللي عندي كالعادة, بس قالولي إن الأماكن الموجودة مش مناسبه, و مش راضيين يوضحوا أي تفاصيل, طيب أنا كويس ولا وحش؟ أنا عكيت ولا إيه نظام؟ طب أنا مستوايا أقل ولا أعلي من المطلوب؟ معرفتش أخرج منهم بأي حاجة مفيدة, قالولي إنهم لو فضي مكان في حتة في ميكروسوفت مناسب ليا هيكلموني, و دمتم, أنا اعتبرته رفض بس بالذوق و قلت فيهم الخير مش عايزين يقولولي في وشي

    المشاكل اللولبية في التجربة المهلبية

    المشكلة بكل بساطة إني كنت أوفر Open-mouthed smile

    اللي حصل إني كنت قاري الكتاب المذكور سابقا بتاع الويندوز بروجرامنج و إتعلمت حاجات جديدة كتير في الشغل الجديد, فكان عندي كمية معلومات كتيرة عرفتها في وقت قصير و ده من فضل ربنا عليا, و كان نفسي بأي طريقة أوصل لميكروسوفت إني كويس و أستحق أشتغل عندهم عشان أعرف كل المعلومات التنينية دي, و ده عبط طبعا, و ده إنعكس إني كنت ببقي أوفر و أنا بجاوب, كنت بحاول أستغل كل الحاجات المتقدمة – مرضتش أقول أدفانسد, خليني ساكت – اللي قريتها مؤخرا في حلولي حتي لو هي مش مستاهلة, و طبعا ده مش صح, هقول أمثله أحسن هتوصل أنا قصدي إيه أفضل من 100 وصف

    Design and Implement a string class to be used by Microsoft developers

    سؤال بسيط و سهل و محفوظ و مش محتاج أي تحور, أي بني أدم عاقل واعي هيعمل مثلا

  • Default and Non-trivial constructors, e.g MyString(const char*)
  • Copy constructor
  • Equality operator ==
  • Assignment operator =
  • Indexing operator []
  • Append string method
  • Length property

و يكتب الهيدر بتاع الكلاس و ي إمبليمينت 3 او 4 حاجات و هو و وقته, و اللي ميلحقش يعمله يتناقش فيه مع الإنترفيور

العبد لله بقي كتب الهيدر بتاع الكلاس و قفش في ال كونستركتر و قعد يكتب فيه طول الإنترفيو و مخلصهوش, واحد يقولي إيه الهبل ده, أقولك عندك حق و أنا مش زعلان منك, أنا فعلا بستهبل, ليه؟ قولتلي ليه؟ جميل, أقولك

الحتة الجاية دي محتاجة إنجليزي معلش عشان الصورة توصل, فاصل و نعود

  • I tried to show him that I know Windows Programming, and I trated characters as TCHAR, which is defined as char (1 byte) if code compiled in ASCII or unsigned short (2 bytes) if code compiled as UNICODE, and this implies using the generic string _t*  functions, (e.g _tcscpy instead of strcpy), and the _T( ) or TEXT( ) macros
  • I tried to show him how I write secure code by using the _t*_s functions (e.g _tcscpy_s instead of _tcscpy)
  • I tried to use the Windows Programming Hungarian notation and coding convention (m_pszStr, p_pszSrcStr, etc..)
  • I raised the discussion of how will I allocate memory to hold the copied string in case of the Non-trivial, Copy constructors and the assignement operator, and spent a lot of time discussing and writing its code. Consider the following constructor which initializes MyString object with a copy of src string through MyString::MyString(char* src)
    A simple straightforward implementation would be:

    MyString(const char* src) : buffer(NULL), length(0)


      if (src != NULL)


        size_t srcLen = strlen(src)

        if (srcLen > 0)

          buffer = new char[srcLen + 1];
          strcpy(buffer, src);
          length = srcLen;

Simple enough, and could do the work. But I went beyond simplicity and forgot myself. Simply:

أنا عديت الفلنكات

I spent the whole interview discussing how to write the memory allocation line:

buffer = new char[strLen + 1];

I told the interviewer that there are many ways to perform this memory allocation. I told him that we can use:

  • Windows Virtual Memory (VirtualAlloc)
  • C Run Time library (new and malloc)
  • Process Heap (HeapAlloc) and raised the issue of whether to use process default heap or create a dedicated heap for string allocations.

He discussed with me the advantages and disadvantages of each method, and I told him that I will choose VirtualAlloc over the others and told him my reasons. I started to write the constructor code but unfortunately I spent the rest of the interview writing the constructor implementation, and I didn’t implement any other MyString method.

نرجع عربي بقي, العربي حلو مفيش كلام

طبعا اللي أنا عملته ده من ابشع الغلطات الي ممكن تعملها في إنترفيو, ألا و هي إنك ما تجاويش علي المطلب الأساسي و تتفرع في مواضيع فرعية متسألتش عليها لدرجة إنك تخلص من غير ما تدي الإنترفيور اللي هو عايزه. يعني كان ممكن أخلص اللي مطلوب مني و بعد كده أقوله علفكرة ده كان ممكن كذا كذا و بقيه النقاش يبقي مثمر, لأن الراجل إتأكد إني عارف أعمل الحاجة الأساسية و عندي إضافات. فنصيحة

قبل ما تتسرع و تجاوب, لازم تفكر إذاي توصل للحل بسرعة بأبسط الطرق, و بعد ما تديله اللي هو عايزه, إبدأ ناقشه في الإضافات اللي إنت تعتقد إنها هتخدم موقفك

طبعا نفس الموضوع كان في السؤال التاني بتاع الهارد درايفر, أفورت برضه في الحل و التفكير, و إتباعي لنفس الإسلوب الأوفر في أكتر من إنترفيو إدي إنطباع إني مش بعرف أرتب تفكيري و مش بعرف أوظف قدراتي كويس, و ده مش مقبول طبعا

أنا كنت متأثر كتير بإني عندي معلومات كتير و كنت عايز أظهرها كلها, بس للأسف طريقة العرض مكانتش مناسبه, و الموضوع جه بالعكس

التجربة الأخيرة في بيتنا بالترنك

بعد تجربة شرم شيخ يجي ب 4 أشهر مثلا لاقيتهم بعتولي لوحدهم من غير ما أقدم و بيقولولي إني عديت أول مرحلة في الإنترفيوهات و إني إتأهلت للفينال راوند, دول يا إما بيستعبطوا يا إما أمي دعيالي دعوه حلوة ساعة أذان. المهم أنا محاولتش أسأل أو أفهم إذاي و أنا مقدمتش, مصدقت و قفشت في الفرصة و قلتلهم أنا دايس

عملت الإنترفيوهات كلها علي حاجة إسمها ميكروسوفت ميتنج صوت بس من غير صورة, و كان فيه بورد برسم عليها لو عايز أوضح أي حاجة و مكان أكتب فيه كود, كانت حاجة ظريفة جدا

عملت 4 إنترفيوهات تقريبا و الحمد لله أديت فيهم كويس و حاولت أتجنب الأخطاء اللي كنت بقع فيها علي قد مقدر الحمد لله, من أكتر الحاجات اللي عجبتهم فيا إني كل حاجة بحاول أرسمها و أوضحها علي البورد أو أرسم ديجرام أوي أي نوع من أنواع الرسم و دي حاجة كانت مكيفاهم جدا, و تعمدت أكتر منها لأن في تركيا كانوا مبسوطين من النقطة دي و قالولي إني بعملها كويس, ففرصة ذي دي ما تضيعش و الواحد يبقي صاحي للكلام اللي بيتقاله كويس

السؤال الوحيد اللي فاكره في الإنترفيو هو

  • Problem: Design and implement a board class to be used by board games like chess that acts as a container for the board objects (e.g for chess the board is container for Pawns, Bishop, Queen, etc..)
  • I consider this question an open-ended question, because you have a lot of design decisions to take, and everything is possible
  • I decided to write a generic template abstract board class and implement its concrete methods.

الحمد لله الموضوع كان سلس و إتقبلت و صار بيا الحال إلي ما أنا إليه دلوقتي و لله الفضل

سنك كــــام؟

lanshonالتجارب دي أكدتلي علي أهمية الخبرة العملية, أنا قريت كتير عن الإنترفيوهات و حضرت كورسات و عملت إنترفيوهات لناس في الأنشطة الطلابية, و كنت معتقد إن ده هيساعد لما أبقي في موقف اللي بيتسأل و هعرف أسد و الموضوع محتاج بس الواحد يحط التتش بتاعته و الموضوع هيعدي بالسنس, بس طلع إعتقادي مش صحيح, مفيش شيء يغني عن التجربة العملية مهما حصل

كان لازم أترفض مرة و إتنين و أعك كتير عشان أعرف مشاكلي و عيوبي, لأني طول ما أنا قاعد في بيتنا مش بجرب نفسي مش هفرق كتير عن كوز اللانشون



oliveالمحصلة من كل اللي أنا بهري فيه, إنك متقعدش في بيتكم و إبدأ قدم في الشركة اللي نفسك فيها, و إترفض و إعرف عيوبك, طور من نفسك, و قدم و إترفض تاني موراكش حاجة, و إترفض تالت و رابع طالما كل مرة بتطور من نفسك و حاسس إن فيه تطور, و ربنا مش هيضيع سعيك و جهدك و خليك واثق في كده

و حط في بالك إن الشغل ده رزق, المهم تسعي, و متبقاش متسرع و عايز تشوف نواتج بسرعة, لما تبقي مستعد هتلاقي الشغل جايلك مستريح

اللينك ده أنا مجمع فيها حبة حلويات, دي الحاجات اللي كنت براجع منها قبل الإنترفيوهات

إعتذار واجب

أنا بعتذر عن إني كتبت كلمات إنجليزي بالعربي (ذي إتش أر, بروجرامنج, إنترفيور, و غيرها من الكلمات الفصيلة) بس الغاية تبرر الوسيلة, اللي يهمني إن المعني يوصل و أتمني إنه يكون وصل فعلا, للأسف مكنش قدامي غير كده لأن “وورد بريس” عنده مشاكل في ميكس عربي من إنجليزي

من المرة الجاية إن شاء الله هبدأ أتكلم عن شغلي الجديد

دعواتكم بقي

SDET Daily’s: Backtracking (aka Flashback) Part1

Before I start talking about anything related to my new work, I prefer to dedicate some posts to talk about the era before Microsoft in general and my journey from Cairo to Washington specifically,. I will talk about the The Fellowship of Microsoft =D


To Microsoft or not to Microsoft ?

Whether you like Microsoft or not, or you are a geek Linux user who feels like you want to puke on seeing MS Windows. I will not try to make you like Microsoft, I don’t have to, I will just try to mention why MS is my starting point.

MS is not my destination, but rather it is a node in my plan graph, What a geeky sentence !!!

تراني تأثرت, لحظة أبكي

Part of my plan is to work in Game Industry, and applying for a game dev position an international game dev company in USA from Egypt is not guaranteed to be a successful trial for many reasons. Not being a USA resident is one of the biggest. Once you are in here, applying in any company is a piece of cake. All-star companies like (Google, Facebook, Amazon, Linkedin, EA games, etc..) are few minutes may be few hours from where you live.

Believe it or not, since I updated my profile info on www.linkedin.com with my new title at MS, city and state, In 1 week I have been contacted by Google, Amazon, Game Studio asking me if I am interested in their positions. Why this didn’t happen to me in Egypt? Simply because such companies don’t spend as much as MS in the recruiting process which is very expensive. They want to save efforts and money, and let MS do the hard work represented in filtering good engineers and bringing them to USA, and then once these quality engineers are in USA,  the engineer hunting war begins. As an example, MS can simply:

  • Make a recruitment event in Turkey, Dubai, Sharm-ElSheikh, or wherever and ticket flights and hotels for all their candidates around the world.
  • Be responsible for all the fees and VISA paper work (which is the hardest part because it consists of dealing with the USA government) and assist you in getting your VISA in Egypt as much as possible.
  • Ticket your flight and bring you to USA. Only few companies here can do this, and if they do they don’t do it a lot, because it is very expensive.
  • Each year, there is a quota of how many H1B visas (a temp worker visa valid for 3-years) can be given to all companies in USA. All companies share this quota, and each year all companies (like Microsoft and Facebook)  who bring new employees from foreign countries’ apply for each candidate to get his H1B visa. Microsoft is known in USA to be a big eater of the H1B quota. There is a big army of engineers working in MS, more than 50K employee including the engineers!

MS can be your journey start-point. MS will help you put your feet in USA.

Whether you will be SDE or SDET working in Windows Automotive, XBOX, Bing, Office, or whatever team. You will learn a lot, regardless of the field you are working on. Working in the biggest software company on Earth is an experience itself, specially if you plan like me to make your own-startup in Egypt.

I will stay in MS as long as it servers my plan. If I find an opportunity in Microsoft Studios I may go for it. If I find another position inside or outside MS that gets me closer to game industry I will go for it, else I will stay in my current team Windows Embedded Automotive, it is a great team and very interesting and I am very excited to be part of a team changing the face of car-driving experience in the World.


وَعَسَى أَنْ تَكْرَهُوا شَيْئًا وَهُوَ خَيْرٌ لَكُمْ وَعَسَى أَنْ تُحِبُّوا شَيْئًا وَهُوَ شَرٌّ لَكُمْ وَاللَّهُ يَعْلَمُ وَأَنْتُمْ لَا تَعْلَمُونَ

SDET Daily’s: Gratz, and Welcome On-Board!

I am officially a MS employee, and I think that this is a great step in my software engineering career path. My start date was 3-DEC-2012. I work at Microsoft Windows Embedded Automotive Team which I will talk about more in later SDET Daily’s posts. My office is at Advanta-C building, Washington, Bellevue. Which is where Windows Embedded monkeys work.

What is SDET Daily’s?

This is the first post in SDET Daily’s series of posts isA. In which I will talk about my technical and non-technical experience here. I will talk about the shock I got from changing cultures. I will talk about the challenges and problems I face here whether technical or non-technical, and when I say non-technical then I mean anything non-technical related to work (e.g position duties, work environment, team organization, atmosphere, etc..), or non-technical experience related to daily life (e.g culture shock, food, spiritual life, and life in general).

You can’t imagine the shock I had on my first day at US

. How everything is organized and in order. How people are friendly and cheerful. How people are well-behaved and respect law. How people are determined and serious. How life is practical. How these people are Muslims with no Islam.

Simply, I will try to draw an image for you about what is going on here in general, and what I do here specifically.

Why SDET Daily’s?

From the beginning, I`d like to tell you about – and in the same time remind myself – Why I am here in general? Clearly, I am here to do 3 things: 1.Learn well, 2. Gain contacts network, and 3. Earn my living. These 3 goals are part of my plan in which I should go back to Egypt and start my own business with friends.

What we care about here is the learning goal. I will try to document some of my experience as I said before,  and I hope that my future posts motivates people to work harder, and realize what is going on in a parallel universe called USA.

Next Post (isA)

I will talk about my first week at work. I wasn’t productive at all because I don’t understand anything yet, and I don’t know what the hell these monkeys are doing!


First of all and before anything, I should thank Allah for giving me this unique opportunity which is more of a gift I don’t deserve. I hope to use it well and achieve my goals fast and return back to my beloved home country Egypt and open my own start-up.

I`d like to thank my family and friends for always supporting me, giving me hope and motivating me. I miss all of you here, isA we will meet soon.

To be continued …

C++ OOP Performance Tips–Part 1

We often encounter inheritance and composition implementations that are too flexible and too generic for the problem domain. They may perform computations that are rarely or never required. In practice, it is not surprising to discover performance overhead associated with inheritance and composition. This is a tradeoff between code reuse and performance. Oftentimes, reusable code will
compute things you don’t really need in a specific scenario. Any time you call functions that do more than you really need, you will take a performance hit. This article will highlight some of these scenarios.

This is not to say that inheritance is fundamentally a performance obstacle. We must make a distinction between the overall computational cost, required cost, and computational penalty. The overall computational cost is the set of all instructions executed in a computation. The required cost is that subset of instructions whose results are necessary. This part of the computation is mandatory; computational penalty = overall computational costrequired cost. This is the part of the computation that could have been eliminated by an alternative design or implementation. (e.g inheritance hierarchy, composition layout, etc…)

So we cannot make a blanket statement that complex inheritance designs are necessarily bad, nor do they always carry a performance penalty. All we can say is that overall cost grows with the size of the derivation tree. If all those computations are valuable then it is all required cost. In practice, inheritance hierarchies are not likely to be perfect. In that case, they are likely to impose a computational penalty.

Constructors and Destructors

Following is a snippet from Visual Studio 2008 Disassembly Window for a simple Foo() function creating Point object locally on the stack and destroying it on returning.

class Point
    Point() : X(0), Y(0) { cout << "Hello!\n"; }
    ~Point() { cout << "Bye bye\n"; }
    int X;
    int Y;

void Foo()
010820B0  push        ebp  
010820B1  mov         ebp,esp 
010820B3  sub         esp,8 
    Point obj;
010820B6  lea         ecx,[obj] // Pass obj address to the constructor 
010820B9  call        Point::Point (10813ACh) // Call Constructor 
010820BE  lea         ecx,[obj] // Pass obj address to the destructor
010820C1  call        Point::~Point (10813B1h) // Call Destructor
010820C6  xor         eax,eax 
010820C8  mov         esp,ebp 
010820CA  pop         ebp  
010820CB  ret             

The translated assembly instructions of each C++ statement (in black) appears directly below it. As you can see, constructors and destructors (in Red) are normal functions like any C++ function. The compiler knows exactly where and when to call them. A constructor or destructor call costs 2 assembly instructions.

The following is the code generated for an empty Point constructor, total of 8 assembly instructions.

class Point
00E12960  push        ebp  
00E12961  mov         ebp,esp 
00E12963  push        ecx  
00E12964  mov         dword ptr [ebp-4],ecx 
00E12967  mov         eax,dword ptr [this] 
00E1296A  mov         esp,ebp 
00E1296C  pop         ebp  
00E1296D  ret   

The following is the code generated for an empty Point destructor, total of 7 assembly instructions.

00E12580  push        ebp  
00E12581  mov         ebp,esp 
00E12583  push        ecx  
00E12584  mov         dword ptr [ebp-4],ecx   
00E12587  mov         esp,ebp 
00E12589  pop         ebp  
00E1258A  ret        

Let’s calculate a base-line for the number of assembly instructions required to construct/destruct a Point object:

  1. 2 instructions to call Point constructor Point::Point().
  2. 8 instructions to implement Point empty constructor body.
  3. 2 instructions to call Point destructor Point:~Point()
  4. 7 instructions to implement Point empty destructor body.
  5. Total of 2 + 8 + 2 + 7 = 19 instruction to construct/destruct a Point object!
    Enough theory, let’s get our hands dirty and write some code and figure out the effect of these extra 19 instruction.
    Consider the code snippet below (Version 0):
// Version 0
Point dummy
; for (int i = 0; i < 100000000; ++i) { Point p; p.X = p.Y = i; dummy.X = p.X; dummy.Y = p.Y; }

The above code doesn’t make sense in a real-life program, and it is meaningless, but it will help illustrate our theory.  We will focus only on the Point object construction/destruction. As you can see, each iteration costs 19 instruction (mentioned up) per Point construction/destruction, and the overall cost for construction/destruction in the previous for-loop is 20 multiplied by the number f iterations which is 100 million ~= 1900000000 instruction only for Point construction/destruction.  Note that we didn’t calculate the instructions required for p and dummy objects members initialization because they are irrelevant to our case-study. We care only for Point construction/destruction.

A make-sense optimization for the previous for loop is to bring the Point p; line outside the for loop so that the Point object is constructed/destructed only once. In theory, the overall construction/destruction should drop from 1900000000 to 20 ! We can call this overhead: “Silent Overhead”.

The optimized for loop will look as follows (Version 1):

// Version 1
Point p
; Point dummy; for (int i = 0; i < 100000000; ++i) { p.X = p.Y = i; dummy.X = p.X; dummy.Y = p.Y; }


We chose number of iterations to be a rather very high 100000000 iteration to highlight the performance drop. Our experimental computer is equipped with a very fast Intel Core i7 processor with 8 logical processors. And 1 million iteration is too small for it, the i7 was able to execute 1 million iteration in 2 milliseconds in average !! That’s why we chose a very high number of iterations to scale this difference.


For Version 0 and Version 1, We ran the for-loop for 100 million iteration and take the average running time for 100 sample. The optimized Version 1 is approximately 3 times faster than Version 0 .

From the previous experiment, It is obvious that object construction/destruction can lead to a big drop in performance if they are called unnecessarily as in code snippet Version 0.

Key Points

  1. Watch out for the combinatorial explosion of created objects in complex hierarchies. The construction (destruction) of an object triggers recursive construction (destruction) of parent and member objects.
  2. Defer object construction (i.e local variable declaration, dynamic object allocation) to the scope in which it is manipulated. The object life cycle is not free of cost. At the very least, construction and destruction of an object may consume CPU cycles. Don’t create an object unless you are going to use it.
  3. Use the object constructor initialization list to complete the member object creation. Because compilers must initialize contained member objects prior to entering the constructor body. This will save the overhead of calling the assignment operator later in the constructor body. In some cases, it will also avoid the generation of temporary objects.

Do/ Don’t Do

Do this:

void Foo(int n)
    if (n == 0)
        HeavyClass heavyObj;

Don’t do this:

void Foo(int n)
    HeavyClass heavyObj;
    if (n == 0)

Do this:

class Person
    Person(const char* name) : Name(name) {}
    string Name;

Don’t do this:

class Person
    Person(const char* name) /* Name constructor called */
        Name = name;
    string Name;


  • Efficient C++ Performance Programming Techniques book By Dov Bulka, David Mayhew

Roots of Software Inefficiency

Being a GEEK ACMer or TopCoder beast (i.e design and analysis of algorithms) is about writing an efficient algorithm in the scope of 3 or 2 functions doing a very specific and limited task. However, writing a software that runs on customers’ computers is bigger than this. A typical windows commercial mid-sized software consists of a set of Executable, Services and DLLs interacting with each other to shape what is called software. The efficiency of algorithms and data structures is necessary but not sufficient: By itself, it does not guarantee good overall program efficiency. It is important to know the roots of software inefficiency if we care about writing fast one.

What are the factors that affect efficiency? Efficient C++ Performance Programming Techniques book By Dov Bulka, David Mayhew made a very good high-level categorization to these factors:

Design Efficiency This involves the program’s high-level design. To fix performance problems at that level you must understand the program’s big picture.  We are talking here about software architecture, UML diagrams, pseudo codes, algorithms, data-structures, and anything you can consider it language independent.

Code Efficiency Small-to medium-scale implementation issues fall into this category. Fixing performance in this category generally involves local modifications. For example, you do not need to look very far into a code fragment in order to lift a constant expression out of a loop and prevent redundant computations. The code fragment you need to understand is limited in scope to the loop body.

Both these 2 levels can be broken down more:

1. Design

1.1 Algorithms and Data Structures Technically speaking, every program is an algorithm in itself. Referring to “algorithms and data structures” actually refers to the well-known subset of algorithms for accessing, searching, sorting, compressing, and otherwise manipulating large collections of data. Oftentimes performance automatically is associated with the efficiency of the algorithms and data structures used in a program, as if nothing else matters which is inaccurate.

1.2 Program Decomposition This involves decomposition of the overall task into communicating subtasks, object hierarchies, functions, data, and function flow. It is the program’s high-level design and includes component design as well as inter-component communication. Few programs consist of a single component. A typical Web application interacts (via API) with a Web server, TCP sockets, and a database, at the very least.

2. Coding

2.1 Language Constructs A programming language is a tool we use to express to computers how to do a specific task. Whether you use C++, C#, Java and you care about performance, you need understand the cost of your programming language constructs so not to be shocked at run time when you program scale. C++ adds power and flexibility to its C ancestor (i.e Object Oriented capabilities). These added benefits do not come for free—some C++ language constructs may produce overhead in exchange.

2.2 System Architecture System designers invest considerable effort to present the programmer with an idealistic view of the system: infinite memory, dedicated CPU, parallel thread execution, and uniform-cost memory access. Of course, none of these is true—it just feels that way. Developing software free of system architecture considerations is also convenient. To achieve high performance, however, these architectural issues cannot be ignored since they can impact performance drastically. When it comes to performance we must bear in mind that:

  • Memory is not infinite. It is the virtual memory system that makes it appear that way.
  • The cost of memory access is non-uniform. There are orders of magnitude difference among cache, main memory, and disk access.
  • Our program does not have a dedicated CPU. We get a time slice only once in a while.
  • On a uniprocessor machine, parallel threads do not truly execute in parallel—they take turns.

If you write Windows software, you need read well about WinAPI and dig deep in Windows programming world, to understand how your host operating system – Windows in this case – will execute your program. This applies if you write software for Linux, iOS or any operating system. Good understanding of the host operating system is a must.

2.3 Libraries The choice of libraries used by an implementation can also affect performance. For starters, some libraries may perform a task faster than others. Because you typically don’t have access to the library’s source code, it is hard to tell how library calls implement their services. For example, to convert an integer to a character string, you can choose between
sprintf(string, “%d”, i); or an integer-to-ASCII function call, itoa(i, string); Which one is more efficient? Is the difference significant?

There is also the option of rolling your own version even if a particular service is already available in a library. Libraries are often designed with flexibility and reusability in mind. Often, flexibility and reusability trade off with performance. If, for some critical code fragment, you choose to put performance considerations above the other two, it might be reasonable to override a library service with your own home-grown implementation. Applications are so diverse in their specific needs, it is hard to design a library that will be the perfect solution for everybody, everywhere, all the time.

2.4 Compiler Optimizations Simply a more descriptive name than “miscellaneous,” this category includes all those small coding tricks that don’t fit in the other coding categories, such as loop unrolling, lifting constant expressions out of loops, and similar techniques for elimination of computational redundancies. Most compilers will perform many of those optimizations for you. But you cannot count on any specific compiler to perform a specific optimization.For ultimate control, you have to take coding matters into your own hands.

I remember how Visual Studio saved my team in an Image Processing performance competition in my faculty. In this competition your image processing package has to run many image processing algorithms and your package timing in each algorithm is used to rank it among the others. We optimized some of our algorithms manually, but didn’t have much time to optimize the others. I got an evil idea of enabling Visual Studio code optimization, and I was shocked by the results. The running time of many algorithms dropped down greatly and I couldn’t believe how C++ code optimization held by the compiler can be that effective.


  1. Teach yourself how to design and analyze algorithms and practice well (i.e problem solving through ACM Online Judge and TopCoder)
  2. Pick a programming language and master it (i.e read about its internals and understand the scary dark side of it).
  3. Know the internals of a certain operating system on which you prefer to write your software (e.g Windows, Linux or Mac OS programming).
  4. Write big multi-file, multi-module projects with real requirements.

Someone Asked: How to Achieve High Marks?

Someone has asked me before how to get high marks in our college. I replied him with the following answer. I`d like to share it with you.
First of all we must admit that high marks in our college is not the measure, also low marks is not a good indicator about the person.
I am not telling here the right “How to” way, I don’t know if what am saying is applicable to all people. What I have done suited me, and it may not suite others due to differences in environment and the character from person to another. So am sharing with you my personal thoughts and ideas.
The high marks way is achieved through 3 points:

  1. Spiritual
    • This is the most important axis, this may rule the other points and dominate it in effect.
    • Being close to Allah is what one should care about. صلاة الفجر هي ترمومتر الإنسان المسلم, and for sure we know how to be close to Allah, there are many ways to achieve this.
    • Trust that your hard work will not be wasted.
    • Never get disappointed and angry that you did something wrong for a long time, this is what “Shetan” wants. Doing a wrong thing should be followed by a good thing. Such disappointing state tends to make one not able to make any output. NEVER TRAP YOURSELF IN SUCH STATE.
    • High spiritual state help one study faster with comfortable and stable state.
    • A comfortable and stable state will tend to give the person the advantage to answer well in the exam.
    • Being close to Allah will help you in Exam Correction, and this can’t be denied. ربنا بيكرم فعلا في الجزئية دي و عن تجربة
  2. Practical
    • Study:
      • You want to be a one who make a change one day? This person can’t be without science, your beliefs will not change anything.
      • To get a science in our college there is one and only one way, it is reading a book. It is your great teacher.
      • It is not easy to read all books, this requires alot of effort and time. but try to read as much books as you can.
      • Choose 3 or 4 books to read in the term.
      • Don’t depend on the lecture in all subjects.
      • Some subjects tend to be studied from lecture and sections only and there are other subjects that worth studying form books more. (Numerical, OR, etc..)
      • Don’t waste your time in a lecture or a section you will not benefit from. Studying form the book sometimes is more effective and time saving. Your time is valuable than just missing an attendance.
      • Try to ask your mates about what they took in a similar section you are attending in same week. If you find the section is not useful and may be you already know what all they take, then you may not attend.
    • Projects:
      • A team more than 4-3 persons is not practical, it will not be effective.
      • Divide the work on you, give a task to the one who really know how to do it, others may involve with him, but mainly he is the one responsible for it.
      • Stick to bonuses as much as you can. This will assist you alot in marks and will overcome the attendance marks you missed.
      • For one wanting to be a scientist, bonuses is the golden result of projects, they are extra work for extra knowledge and extra marks.
    • Exams:
      • If you don’t attend lectures then make sure to know what doctors will focus on in exams by asking people attending the lectures. Doctors tend to give hints to those who attend last lectures.
      • From my observations, in final exams, doctors focus more on what have been studied after the midterm, s/he already tested you in what is before midterm.
      • Make sure to check exams of previous years to know what you need to stress on, sometimes it is very helpful to test your self-study knowledge.
      • Make sure to check the slides, it will tell you what actually the doctor gave in the lectures. the doctor skip some sections in the chapter and this will help you not to focus on study on it especially if it is definitions.
      • In the solution paper, don’t hesitate to give hints and illustrations using the pencil about your solution when applicable.
      • Sometimes you solve using some special notation, make a box and write your notations in it, it is OK as long as you don’t go off the topic.
      • There are some things I used to do, When I receive the answers paper I immediately flip it, and say some “Quran” and “Azkar” and any do3a2 to comfort myself.
  3. Talents and Skill
    • It is very important for one to know his skills and abilities and benefit from them.
    • If you find your self able to understand things quickly then you may use this skill to focus more on projects than study.
    • It is very insane to do, but it if you are a book worm, then it is very OK to read from books to understand in exam days. You will get a deeper understanding, this will assist you in your answers. and you will be proud of yourself.

I hope that I covered the most important things I remember.
والله المستعان

Useful posts discussing the same subject

Changing Thread Path of Execution

Every thread has a context structure, which is maintained inside the thread’s kernel object. This context structure reflects the state of the thread’s CPU registers when the thread was last executing.

Every 20 milliseconds or so (as returned by the second parameter of the GetSystemTimeAdjustment function), Windows looks at all the thread kernel objects currently in existence. Of these objects, only some are considered schedulable. Windows selects one of the schedulable thread kernel objects and loads the CPU’s registers with the values that were last saved in the thread’s context. This action is called a context switch.

The code primary thread (main function) below creates a new thread where its entry point is ThreadFunc1, and while it is running it suspends this secondary and changes its path of execution to the address of another function.


DWORD WINAPI ThreadFunc1(PVOID pvParam)
    _tprintf_s(_T("I am ThreadFunc1\n"));

    _tprintf_s(_T("Exiting ThreadFunc1\n"));

    return 0;

DWORD WINAPI ThreadFunc2(PVOID pvParam)
    _tprintf_s(_T("I am ThreadFunc2\n"));

    _tprintf_s(_T("Exiting ThreadFunc2\n"));
    return 0;

int _tmain(int argc, TCHAR* argv[])
    // create a new thread with ThreadFunc1 as its entry-point
    HANDLE hThread = chBEGINTHREADEX(NULL, 0, ThreadFunc1, NULL, 0, NULL);


    // lets give the thread some time to do some work


    CONTEXT cThread;
    // get control registers such as EIP (instruction pointer)
    cThread.ContextFlags = CONTEXT_CONTROL;
    GetThreadContext(hThread, &cThread);

    // change the target thread path of execution to ThreadFunc2
    cThread.Eip = (DWORD)ThreadFunc2;
    SetThreadContext(hThread, &cThread);


    WaitForSingleObject(hThread, INFINITE);

    return 0;



How process can skip from its JOB – A taste of dirty application

I am writing this post while I can’t believe if what I did is normal or not, I will mention what I`ve did then I will pose some questions that really need answer.

Job Object is a very powerful concept in Windows, and it us used to impose limitations on process assigned to it, some of this limitations enhance process security. For more information about jobs refer Jobs post.

An important information you should know about Jobs:

Once a process is part of a job, it cannot be moved to another job and it cannot become jobless (so to speak). Also note that when a process that is part of a job spawns another process, the new process is automatically made part of the parent’s job. However, you can alter this behavior in the following ways

Let’s consider this scenario:

you write a Host application that runs other applications and manages them, this applications may have unknown implementation (you are not its author), and you create these application as a child process (Client process) of your Host process. Imagine that some of these client process are infected by some virus which requires to cross the limitations you imposed by your Job (e.g spawn other children processes, access USER objects outside the process, etc..). To ensure that your client processes run in a safe environment you impose the necessary restrictions.

Imagine if one application (infected one) was written to skip from the Job assigned to it and run as a jobless process with no restrictions! HOW will you control such thing? This is horrible and this is what I could do! I though that doing such thing is not doable as it is very dangerous, but I could do it.

Dirty application code

#include <iostream>
#include <Windows.h>
#include <tchar.h>
#include <strsafe.h>
#include "XWinAssist.h"
using namespace std;

#define HostJobName _T("XHostJob")
#define AppName _T("cmd.exe")
#define AppCount 5

void CreateJoblessSelf()
    const int cchSize = 128;
    DWORD dwSize = cchSize;
    TCHAR szProcessName[cchSize];
    QueryFullProcessImageName(GetCurrentProcess(), 0, szProcessName, &dwSize);

    STARTUPINFO si = { sizeof(si) };

    // Here I create myself again in the same console window
    // I specify that I want to create myself and skip the current job
    BOOL fCreate = CreateProcess(NULL, szProcessName, NULL, NULL, FALSE, CREATE_BREAKAWAY_FROM_JOB, NULL, NULL, &si, &pi);

        _tprintf_s(_T("Failed to create jobless self\n"));


void StartSomeProcess()
    const int iSize = 128;
    TCHAR szCommandLine[iSize];
    _tcscpy_s(szCommandLine, iSize, AppName);
    STARTUPINFO si = { sizeof(si) };

    // Start some cmd.exe prcess, for sure this can be any process you imagine
    BOOL fCreate = CreateProcess(NULL, szCommandLine, NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi);

        _tprintf_s(_T("Failed to start some process\n"));


int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
    BOOL bInJob = FALSE;
    PROCESS_INFORMATION pi =  { 0 };

    // find if we are already assigned to a job
    IsProcessInJob(GetCurrentProcess(), NULL, &bInJob);

    // I will try to skip from the job already assigned to me
    if (bInJob)
        _tprintf_s(_T("\nProcess already in a job\n"));
        _tprintf_s(_T("Spawining JOBLESS SELF …\n"));

        // instantiating myself but with no restrictions

        _tprintf_s(_T("\nRestarting …\n"));
        return 0;
        // Reaching this line means that I am totally free and have no job restrictions
        _tprintf_s(_T("\nMUHAHAHAHA … I am JOBLESS Process (Evil Laugh)\n"));

    // Spawn some process to mobilize system resources
    // this could be some other infectious job
    for(int i = 0; i < AppCount; ++i)



  • Microsoft Win7 Professional
  • Visual Studio 2008 Team Suite

Questions and Exclamations

I have some questions in my mind I need answer for, I tried to search online but with no useful information.

  1. Is there any permission or access rights required to allow a process to spawn other process outside its job? I think there should be some.
  2. Can this behavior be really dangerous and be used to make havoc in the system?
  3. Is this considered as a security flaw?
%d bloggers like this: