-
Notifications
You must be signed in to change notification settings - Fork 4
/
InterviewGeneralLearning.txt
executable file
·3464 lines (2662 loc) · 203 KB
/
InterviewGeneralLearning.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
- READ BLOGS ON PURE
- SHOW A LOT OF CURIOSITY
- ASK A LOT OF QUESTIONS
- THINK OUT LOUD
- HOW MUCH KNOW ABOUT THE COMPANY
- BODY LANGUAGE
- THOUGHT PROCESS
- Even if you come up with the OPTIMAL SOLUTION (Just give the REASONING behind it)
- HOW AM I APPROACHING THE PROBLEM
- PREPARE QUESTIONS TO ASK
- SEE ABOUT EACH INTERVIEWER AND IF YOU HAVE ANY SIMILARITY
1. Don't Jump into Coding
2. First Do Algo Reasoning
3. Clarify all statements
4. Debugging
5. How you approach the solution
6. Keep constraints in mind and validate it after coding
2018:
1. Catch and Throw exception where necessary
- queue.remove(), queue.add() etc
2. Class design, First come up with design
-----------------------------------------------------
Genral Programming / OOPS Concepts
0. What is Abstraction:
1. What is Encapsulation:
2. What is Polymorphism:
3. Encapsulation vs Abstraction:
3a. How are Abstraction and Encapsulation related
3b. Polymorphism vs Overriding vs Overloading:
3c. Why do you need Polymorphism:
4. Overriding:
5. Overloading:
6. What is Inheritence:
7. Is-A vs Has-A
8. Inheritence Vs Polymorphism:
9. Friend Function vs Static Function
10. External Linkage vs Internal Linkage
11. Early binding vs Late Binding
12. Segmentation Fault:
12b. How to create a Segmentation Fault
13. Interrupts vs Exception
14. Callback Functions:
15. Asynchronous Programming:
16. Allocating in Stack vs Heap:
16b. Is Stack Faster than Heap
17. Memory Allocation on Stack Vs Heap
17b. What and Where are Stack and Heap
18. Boxing and Unboxing
19. Shadowing and Overriding
20. Agile Model
21. Types of Polymorphism
22. Compiler vs Interpretor
23. Recursion vs Iterative Approach
24. Tail Recursion Advantages
25. Problems with Multiple Inheritence
26. Static Linking vs Dynamic Linking
27. How to resolve Hash Collisions
28. Multithreading Best Practices
29. What is Amdhal's law
30. UCS-2 vs UTF-8/16/32
31. When will you use ASCII instead of UTF-8?
32. Number of characters in ASCII
33. Unicode and Character Set
34. How to read a file in reverse / Implement Tail / Display last n lines in a file
35. How to programmatically cause a core dump in C/C++
36. How to store a password in database
37. Abstract Class vs Interface - When to use each
-----------------------------------------------
UML / DESIGN Questions
0. Associations
1. Parking lot
2. Coffee Maker
3. Deck of Cards
4. What is Cardinality
5. What are mock Objects
6. UML Diagrams
7a. Design Patters
7b. Factory Pattern vs Singleton Pattern
7c. Abstract Factory vs Factory
8. MVC PAttern
9. Elevator
10. Bike Shop
-----------------------------------------------
OS NOTES
-1. Every program assumes it has its own memory space
-1b. Memory allocation at compile time
-1c. When we associate '&' with a variable the address we get is the virtual address or the physical address? [duplicate]
-1d. What determines the size of an executable
0. Differentiate Threads and Processes
0b. Explain Multithreading to a 5year old
1. What is a Race Condition
2. Mutex vs Semaphores:
3. Spin Locks vs Mutex:
3a. Mutex Monitor and Semaphore
3b. Spin Lock in a Uniprocessor System
3c. Lock Monitor Mutex and Semaphore
3d. Monitor vs Semaphore
3e. Monitor vs Mutex
3f. Semaphore vs Condition Variable
4. Multi-threaded programming in C++
4b. Thread Join vs Detach
5. Hard Link vs Soft Link
5b. What is an Inode ?
5c. How is data stored? Direct referencing, Double indirect and triple indirect
6. Multi Processor vs Multi Core System
7. What is a File descriptor
8. Why can't RAM be replaced by Cache memory
9. How to avoid deadlocks
10. Latency vs Throughput
11. What is Page Fault
12. Why do we need Paging, Unequal Size Fixed Partitioning and Dynamic Partitioning
12b. If we have infinite memory, then do we still be needing paging
13. What is Virtual Memory
14. Why do we need Virtual Memory
15. Where is Page File / Virtual Memory Stored
16. What is Resident Set Size (RSS) and Virtual Memory Size (VSZ)
17. Paging vs Swapping vs Trashing
18. Why does a 32-bit OS support 4 GB of RAM?
19. MB vs MiB / GB vs GiB
20. SRAM vs DRAM
21. Spurious Wakeups
-----------------------------------------------
NETWORKS
0. How TCP Works:
1. How TCP/IP Network works
1b. How Internet Works
1c. TCP vs UDP
1d. Can two applications listen to the same port
1e. Do browsers listen to port 80?
1f. Do web browsers use different outgoing ports for different tabs?
2. Why is MAC address required
3. Switch vs Hub vs Router
4. How NTLM Authentication Works
5. How Kerberos Authentication Works
5b. NTLM vs Kerberos
6. What happens when I click the Stop button on the browser
7. what happens when you type in a URL in browser
8. What is DHCP and how it works
9. How WiFi (802.11) works
10. DNS and how it works
11. What is NTP and SNTP
12. What is TLS and SSL
13. What is DHCP
14. Sliding Window Protocol
15. What is LDAP
16. What is Samba
17. What is SMB
18. Ports vs Socket
19. TCP Port and UDP Port
20. IPv6
-----------------------------------------------
SECURITY
1. Asymmetric and Symmetric Encryption
2. What is SSL Termination
-----------------------------------------------
MISC
1. What is REST Service
1b. GET vs POST
1c. GET, POST, PUT, DELETE, PATCH
1c. RPC vs REST
1d. RESTful API is stateless
1e. What exactly is RESTful programming?
1j. REST API Critical data won't be passed in the URL
1k. Can a GET request have a body
1l. Types of REST API parameters
1m. HTTP vs HTTPS
1f. IIOP
1g. RMI
2. What is a Websocket
3. Relational Database vs NoSQL Database
4. ACID Properties in DB
5. BASE Properties
6. Tabs vs Spaces as Coding Style
7. JSON vs JSON-LD
8. Springboot
8a. Spring vs Springboot
8b. What Is Spring Initializr?
8c. What Basic Annotations Does Spring Boot Offer?
8d. What is the difference between RequestMapping and GetMapping?
9. Types of Dependency Injection
10. TRUNCATE vs DROP in DB
-----------------------------------------------
DISTRIBUTED SYSTEMS:
--------------------------------------------------------------------------------
BEHAVIORAL QUESTIONS
1. Disagree with Manager / Team Member
Deadline Scheduling
- Situation:
- For a new project my manager initially thought it could be done in a week. I had a disagreement there that we would need 3 weeks for that to completely deliver the product
- Task
- Building a system to sync changes between source and target
- Action
- I split the project into multiple modules and explain in detail how long each module will take
- About integration of the modules
- Performing regression testing on the entire module
- Also creating a test bed for the environment
- Result
- We were able to deliver the product with high quality and on time
- If we had rushed through in two weeks, we might not have done a thorough
testing. Might also went with a quicker way to do things instead of going with a scalable way of doing things
Developing Abstract Notification Adapter
- Situation
- First make few API calls to Storage subsystem to create a new FPolicy config
- Later got a separate project which heavily uses the config
- Didn't have time to make the switch from old to new as it was already out with customers
- Task
- Had to create a generic adapter
- Action
- Had a knob to switch back to old mechanism in case of any failure
- Designed the new one in a completely abstract way
- Result
- Amazing generic notification adapter
2. Customer Obsession:
POC Example where we failed to configure on storage systems
I have worked very closely with customers
How customers would configure / unconfigure
- Where they would like to select multiple entries and perform "enable all" / "disable all"
Multi-node cluster setup
3. Highest Standards:
- Coding standards
- Comments
- Documentation etc
4. Ownership:
- Own NetApp and EMC storage systems
--------------------------------------------------------------------------------
GENRAL PROGRAMMING / OOPS Concepts
0.
What is Abstraction:
- Abstraction is the concept of ignoring unnecessary details.
- Or other words, describing something in a simpler way by not concentrating on the intricate details and focusing only on necessary details.
- It can be thought as generalization.
- Say when you are meeting a random person, you would say that you are the guy in Black Shirt and Blue Jean.
- We can consider Interfaces as Abstraction.
1.
What is Encapsulation:
- Encapsulation is something like group similar things in a box.
- So someone else won't have access to the inside of the box. They can just use the box to do what they want.
- Changing the contents of the box won't affect the outsider. They will still be able to use the box.
2.
What is Polymorphism:
- Polymorphism is the ability to an object to decide what it should.
- Simple example would be to consider "Shapes" class. And the class has methods like Area and Cirumferance.
- We can have subclasses like Square, Rectangle.
- To find the area of all the shapes, we can just give Shapes.area(). Based on what shape it is, we will get the respective Area.
3. Encapsulation vs Abstraction:
VERY IMP:
http://stackoverflow.com/questions/12072980/encapsulation-vs-abstraction-real-world-example
http://blogs.siliconindia.com/deepvijay/Technology/Encapsulation-and-Abstraction-a-real-time-example-bid-wvGh8f5F89208310.html
Encapsulation puts some things in a box and gives you a peephole; this keeps you from mucking with the gears.
Abstraction is the process of generalization: taking a concrete implementation and making it applicable to different, albeit somewhat related, types of data. The classical example of abstraction is C's qsort function which sorts data.
Encapsulation:-- Information hiding.
Abstraction:-- Implementation hiding.
Example:
class foo{
private:
int a, b;
public:
foo(int x=0, int y=0): a(x), b(y) {}
int add(){
return a+b;
}
}
Internal representation of any object of foo class is hidden outside the class. --> Encapsulation.
Any accessible member (data/function) of an object of foo is restricted and can only be accessed by that object only.
foo foo_obj(3, 4);
int sum = foo_obj.add();
Implementation of method add is hidden. --> Abstraction.
Abstraction:
The thing about qsort is that it doesn't care about the data it sorts in fact, it doesn't know what data it sorts. Rather, its input type is a typeless pointer (void*) which is just C's way of saying I don't care about the type of data (this is also called type erasure). The important point is that the implementation of qsort always stays the same, regardless of data type. The only thing that has to change is the compare function, which differs from data type to data type. qsort therefore expects the user to provide said compare function as a function argument.
Abstraction is achieved by making class abstract having one or more methods abstract.
Which is nothing but essential characteristic which should be implemented by the class extending it.
e.g. when you inventing/designing a car you define a characteristics like car should have 4 doors, break, steering wheel etc
so anyone uses this design should include this characteristics.
Encapsulation:
Example 1.
A cell phone is a great example.
I have no idea how the cell phone connects to a satellite, tower, or another phone.
I have no idea how the damn thing understands my key presses or how it takes and sends pictures to an email address or another phone number.
I have no idea about the intricate details of most of how a modern smart phone works.
Example 2.
As a driver you know how to start the car by pressing the start button and internal details of the starting operations are hidden from you.
So the entire starting process is hidden from you otherwise we can tell starting operation is encapsulated from you.
Abstraction:
Example 1.
But, I can use a cell phone.
The phones have standard interfaces (yes - both literal and software design) that allows someone who understand the basics of one to use almost all of them.
Example 2.
The car's operation is completely abstracted from you and it is partially implemented to Local Mechanic Entity and fully implemented to Expert Entity.
So you are an abstract class having only abstract methods, Local Mechanic Entity has extended You(Since he is also an ordinary user) and he implemented some of the methods and last our expert Entity extending Local Mechanic and implementing all the methods
Though every method is an encapsulation, it is also an abstraction, because every time you put some things together and give it a name you create a new (abstract) concept. Encapsulation without abstraction is useless.
http://stackoverflow.com/questions/742341/difference-between-abstraction-and-encapsulation
Abstraction flat-out ignores the details that don't matter, like whether the things have gears, ratchets, flywheels, or nuclear cores; they just "go"
Abstraction is hiding the implementation details by providing a layer over the basic functionality.
INFORMATION HIDING, ENCAPSULATION and ABSTRACTION:
Information Hiding is hiding the data which is being affected by that implementation. Use of private and public comes under this. For example, hiding the variables of the classes.
Encapsulation is just grouping all similar data and functions into a group e.g Class in programming; Packet in networking.
- Putting data and behavior together is what I understand from encapsulation.
- Hiding complexity is abstraction.
- Information should remain unseen is what information hiding is. Very famous three sentences.
http://stackoverflow.com/questions/742341/difference-between-abstraction-and-encapsulation
Most answers here focus on OOP but encapsulation begins much earlier; every method is an encapsulation:
point x = { 1, 4 };
point y = { 23, 42 };
int d = distance(x, y);
Here, distance encapsulates the calculation of the (euclidean) distance between two points in a plane: it hides implementation details. This is encapsulation, pure and simple.
3a.
How are Abstraction and Encapsulation related
http://stackoverflow.com/questions/12072980/encapsulation-vs-abstraction-real-world-example
Both abstraction and encapsulation are underlying foundations of object oriented thought and design.
So, in our cell phone example.
The notion of a smart phone is an abstraction, within which certain features and services are encapsulated.
The iPhone and Galaxy are further abstractions of the higher level abstraction.
Your physical iPhone or Galaxy are concrete examples of multiple layers of abstractions which contain encapsulated features and services.
3b.
Polymorphism vs Overriding vs Overloading:
http://stackoverflow.com/questions/154577/polymorphism-vs-overriding-vs-overloading
The clearest way to express polymorphism is via an abstract base class (or interface)
public abstract class Human{
...
public abstract void goPee();
}
This class is abstract because the goPee() method is not definable for Humans.
It is only definable for the subclasses Male and Female.
Also, Human is an abstract concept - You cannot create a human that is neither Male nor Female. Its got to be one or the other.
So we defer the implementation by using the abstract class.
public class Male extends Human{
...
@Override
public void goPee(){
System.out.println("Stand Up");
}
}
public class Female extends Human{
...
@Override
public void goPee(){
System.out.println("Sit Down");
}
}
Now we can tell an entire room full of Humans to go pee.
public static void main(String[] args){
ArrayList<Human> group = new ArrayList<Human>();
group.add(new Male());
group.add(new Female());
// ... add more...
// tell the class to take a pee break
for (Human person : group) person.goPee();
}
3c.
Why do you need Polymorphism:
Say you have MS Company. It creates a Function.
Google, FB, etc are derived classes whose object will be passed to the function that MS has.
It will of the form,
MS ob1 = new Google();
MS ob2 = new FB();
MS can just execute it by doing ob.exec();
4.
Overriding:
- Concept of adding more details to a function in the derived class.
- It replaces the function in the base class.
5.
Overloading:
- It is concept of defining multiple methods based on the parameters passed.
6.
What is Inheritence:
- It is concept where a new class is derived from an existing class.
- This happens when we want to have a new Class that will make use of an existing class with some added details to it.
- Eg we have a Vehicle / Shapes class and we want to add Car / Square class.
- Inheritence should only be used if the sub class is BEHAVIORIALLY equal to the superclass.
7.
Is-A vs Has-A
A House is a Building (inheritance);
A House has a Room (composition);
A House has an occupant (aggregation).
http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance
Does TypeB want to expose the complete interface (all public methods no less) of TypeA such that TypeB can be used where TypeA is expected? Indicates Inheritance.
e.g. A Cessna biplane will expose the complete interface of an airplane, if not more. So that makes it fit to derive from Airplane.
Does TypeB only want only some/part of the behavior exposed by TypeA? Indicates need for Composition.
e.g. A Bird may need only the fly behavior of an Airplane. In this case, it makes sense to extract it out as an interface / class / both and make it a member of both classes.
http://enoshtechdiary.blogspot.com/2012/04/composition-vs-aggregation.html
Usage of Inheritence and Aggregation
- If we have used inheritance but we only use part of the interface, or we are forced to override a lot of functionality to keep the correlation logical.
Then we have a big nasty smell that indicates that we had to use aggregation.
- If we have used aggregation (or we plan to use it) but we find out we need to copy almost all of the functionality. Then we have a smell that points in the direction of inheritance.
HAS-A - ASSOCIATION
1. Composition:
- REPRESENTED using FILLED DIAMOND in a CLASS DIAGRAM
- Composition is an association in which one class CANNOT exisit without other.
- EG: CAR has-a Engine.
- When we destroy CAR, we destroy Object as well.
- CAR manages the lifetime of the Engine.
- OUR TREE STURUCTURE has FILES.
- When we destroy Trees, we destroy Files.
2. AGGREGATION
- REPRESENTED using EMPTY DIAMOND in a CLASS DIAGRAM
- Aggregation is a Composition in which one class belongs to a Collection.
- However it CAN exist without the WHOLE.
- EG: CAR has a DRIVER.
- Multichannel Sessions that can exist even if the Connection goes away.
8. Inheritence Vs Polymorphism:
http://stackoverflow.com/questions/6308178/what-is-the-main-difference-between-inheritance-and-polymorphism
http://www.tutorialspoint.com/cplusplus/cpp_inheritance.htm
// Base class
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
return 0;
}
9.
Friend Function vs Static Function
http://stackoverflow.com/questions/4723143/static-member-functions
http://stackoverflow.com/questions/2315166/where-would-you-use-a-friend-function-vs-a-static-member-function
http://stackoverflow.com/questions/4921150/when-to-use-static-member-function?lq=1
Static Variable:
Lifetime is throughout the program. It will hold valid for all instances of the Class.
Static Function:
PRotected static function.
Good uses of static member functions:
Meta-programming: writing code that writes code; Metaprogramming refers to a variety of ways a program has knowledge of itself or can manipulate itself.
Real-world example is template std::char_traits. All member functions are static
Making it a static member function gives it access to private members of the class, although a friend would suffice here too
A protected static member function thus is accessible only to the class and classes derived from it.
http://stackoverflow.com/questions/2671496/java-when-to-use-static-methods
Ask yourself "does it make sense to call this method, even if no Obj has been constructed yet?" If so, it should definitely be static.
So in a class Car you might have a method double convertMpgToKpl(double mpg) which would be static, because one might want to know what 35mpg converts to, even if nobody has ever built a Car.
But void setMileage(double mpg) (which sets the efficiency of one particular Car) can't be static since it's inconceivable to call the method before any Car has been constructed.
Define static methods in the following scenarios only:
1. If you are writing utility classes and they are not supposed to be changed.
2. If the method is not using any instance variable.
3. If any operation is not dependent on instance creation.
4. If there is some code that can easily be shared by all the instance methods, extract that code into a static method.
5. If you are sure that the definition of the method will never be changed or overridden. As static methods can not be overridden.
Friend
In many situations you will have objects with data or functionality that are not intended to be called publicly available.
Friend function:
It has access to private members of the class.
http://stackoverflow.com/questions/17434/when-should-you-use-friend-in-c
Friend CLASS:
The 'friend' specifier allows the designated class access to protected data or functionality within the class making the friend statement.
For example in the below code anyone may ask a child for their name, but only the mother and the child may change the name.
You can take this simple example further by considering a more complex class such as a Window. Quite likely a Window will have many function/data elements that should not be publicly accessible, but ARE needed by a related class such as a WindowManager.
class Child
{
friend class Mother;
public:
string name( void );
protected:
void setName( string newName );
};
10.
External Linkage vs Internal Linkage
TIC++
- Internal linkage means that storage is created to represent the identifier only for the file being compiled.
- Internal linkage is specified by the keyword static in C and C++
Const defaults to Internal Linkage in C++ and External Linkage in C
- External linkage means that a single piece of storage is created to represent the identifier for all files being compiled.
- The storage is created once, and the linker must resolve all other references to that storage.
- Global variables and function names have external linkage.
- These are accessed from other files by declaring them with the keyword extern.
11.
Early binding vs Late Binding
a. Early Binding:
In Method Overloading your method calls to the methods are decided by the compiler in the sense that which function is going to be called is decided by your compiler at compile time. Hence being EARLY BINDING
Compiler generates a call to a specific function
Runtime system resolves this call to aboslute address of the code
b. Late Binding:
In method Overriding, it is decided at RUNTIME which method is going to be called. So it is reffered as LATE BINDING.
Compiler just ensures that the method exists and performs type checking on args and return value
Compiler DOES NOT know the exact code to execute
- Address of the method is calculated USING the information stored in the object.
12.
Segmentation Fault:
http://stackoverflow.com/questions/2346806/what-is-segmentation-fault
- generates SIGSEGV event
- Segmentation fault is a specific kind of error caused by accessing memory that does not belong to you.
int *p = NULL;
*p = 1;
Another segfault happens when you try to write to a portion of memory that was marked as read-only:
char *str = "Foo"; // Compiler marks the constant string as read-only
*str = 'b'; // Which means this is illegal and results in a segfault
It would be worth noting that segmentation fault isn't caused by directly accessing another process memory, as it is simply not possible.
With virtual memory every process has its own virtual address space and there is no way to access another one using any value of pointer.
Exception to this can be shared libraries which are same physical address space mapped to (possibly) different virtual addresses and kernel memory which is even mapped in the same way in every process (to avoid TLB flushing on syscall, I think). - these are what I count as 'indirect' access.
One can, however, check that they are usually located long way from process code and we are usually able to access them (this is why they are there, nevertheless accessing them in a improper way will produce segmentation fault).
Still, SEGMENTATION FAULT CAN OCCUR IN CASE OF ACCESSING OUR OWN (PROCESS) MEMORY IN IMPROPER WAY (for instance trying to write to non-writable space).
But the most common reason for it is the access to the part of the virtual address space that is not mapped to physical one at all.
12b.
How to create a Segmentation Fault
http://stackoverflow.com/questions/2045314/why-cant-i-cause-a-seg-fault
It impossable to try and reliable do it dereferencing pointers.
This is because how the application handles memory can vary from compiler to compiler also across the same compiler with different options (debug/release mode handeled differently).
What you can do is explicitly raise the segfault using a signal:
#include <signal.h>
int main()
{
raise(SIGSEGV);
}
13.
Interrupts vs Exception
http://stackoverflow.com/questions/125394/interrupts-and-exceptions
WHERE AN EXCEPTION DIFFERS FROM AN INTERRUPT IS THAT AN EXCEPTION IS CAUSED BY SOME ILLEGAL ACTIVITY THAT THE PROCESSOR HAS DETECTED.
Interrupt:
Interrupts are generated by devices external to the CPU (timer tick, disk operation completion, network packet arrival, etc.)
An interupt is a CPU signal generated by hardware, or specific CPU instructions.
These cause interupt handlers to be executed.
Things such as I/O signals from I/O hardware generate interupts.
Eg: Keyboard Interrupt
Your processor is going to have a number of external interrupt pins.
Typically these pins are connected to hardware and are used to indicate when some external event occurs.
Other peripherals like timers, usb controllers, etc. will also generate interrupts on the basis of some external event.
ISR:
When the processor receives a signal on one of it's external interrupt pins it will immediately jump to some nominated location in memory and start executing.
The code executed is typically called an ISR, or interrupt service routine.
TIMER INTERRUPT:
So, let's say I write a simple C program that counts all numbers, or the Fibonacci sequence, or something else without stopping. Or even better: does nothing but spins inside of a while(1) loop. How do the other processes on the system get a chance to run? What if there is nothing happening to cause an interrupt?
The answer is that you have a timer device that is constantly interrupting. And it is what keeps a spinning process from taking down the entire system.
Exception:
An exception can be thought of as a software-version of an interupt, that only affects its process.
There have been 3 different meanings listed in other answers on this page.
SOFTWARE CONSTRUCT:
This is purely an application level exception, where a piece of code is able to indicate an error that can be detected by some other piece of code.
There is no hardware involvement here at all.
TASK EXCEPTION:
Then there is the exception as seen by a task.
This is an operating system level construct that is used to kill a task when it does something illegal - like divide by 0, illegally accessing memory etc.
HARDWARE EXCEPTION:
And thirdly, there is the hardware exception.
In terms of behaviour it is identical to an interrupt in that the processor will immediately jump to some nominated memory location and start executing.
Where an exception differs from an interrupt is that an exception is caused by some illegal activity that the processor has detected.
For example the MMU on the processor will detect illegal memory accesses and cause an exception.
These hardware exceptions are the initial trigger for the operating system to perform it's cleanup tasks (as described in the paragraph above)
14.
Callback Functions:
http://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o
Imagine this scenario: You are expecting a package in a couple of days. The package is a gift for your neighbor. Therefore, once you get the package, you want it brought over to the neighbors. You are out of town, and so you leave instructions for your spouse.
You could tell them to get the package and bring it to the neighbors. If your spouse was as stupid as a computer, they would sit at the door and wait for the package until it came (NOT DOING ANYTHING ELSE) and then once it came they would bring it over to the neighbors. But there's a better way. Tell your spouse that ONCE they receive the package, they should bring it over the neighbors. Then, they can go about life normally UNTIL she receives the package.
In our example, the receiving of the package is the "event" and the bringing it to the neighbors is the "callback". Your spouse "runs" your instructions to bring the package over only when the package arrives. Much better!
This kind of thinking is obvious in daily life, but computers don't have the same kind of common sense. Consider how programmers normally write to a file:
fileObject = open(file)
# now that we have WAITED for the file to open, we can write to it
fileObject.write("We are writing to the file.")
# now we can continue doing the other, totally unrelated things our program does
Here, we WAIT for the file to open, before we write to it. This "blocks" the flow of execution, and our program cannot do any of the other things it might need to do! What if we could do this instead:
# we pass writeToFile (A CALLBACK FUNCTION!) to the open function
fileObject = open(file, writeToFile)
# execution continues flowing -- we don't wait for the file to be opened
# ONCE the file is opened we write to it, but while we wait WE CAN DO OTHER THINGS!
15.
Asynchronous Programming:
In solving many engineering problems, the software is designed to split up the overall problem into multiple individual tasks, and then execute them asynchronously.
Inverting a matrix, or a finite element analysis problem, are good examples.
In computing, sorting a list is an example. The quick sort routine, for example, splits the list into two lists, and sorts each of them by calling itself recursively.
In both of the above examples, the two tasks can (and often were) executed asynchronously.
They do not need to be on separate threads.
Even a machine with one CPU, and only one thread of execution can be coded to initiate processing of a second task before a first one has completed.
THE ONLY CRITERION IS THAT THE RESULTS OF ONE TASK ARE NOT NECESSARY AS INPUTS TO THE OTHER TASK.
As long as the start and end times of the tasks overlap, (possible only if the output of neither is needed as inputs to the other), they are being executed asynchronously, no matter how many threads are in use.
16.
Allocating in Stack vs Heap:
STACK:
SCOPE - Function
Allocating in the stack is easy and fast, but stack is limited,
Apart from that, stack allocated values are "deleted" once you leave the scope, so it is very good for small local values like primitive variables.
If you allocate too much in the stack you might run out of stack and die,
Main as all the functions you execute has a stack frame in the stack and all the local variables to the function are stored there.
So going too deep into function calling might get you into a stackoverflow as well.
In general is a good rule of thumb to allocate anything that you use often and is bigger than a hundred bytes in the heap, and small variables and pointers in the stack.
HEAP:
SCOPE - When you want something to be used outside of the function
heap is slower but much bigger.
In general is a good rule of thumb to allocate anything that you use often and is bigger than a hundred bytes in the heap,
16b.
Is Stack Faster than Heap
http://stackoverflow.com/questions/161053/which-is-faster-stack-allocation-or-heap-allocation
http://stackoverflow.com/questions/24057331/is-accessing-data-in-the-heap-faster-than-from-the-stack
Stack is always hot, the memory you get is much more likely to be in cache than any far heap allocated memory
Stack allocation is much faster since all it really does is move the stack pointer.
Using memory pools, you can get comparable performance out of heap allocation
Stack is much faster. It literally only uses a single instruction on most architectures, in most cases, e.g. on x86:
(That moves the stack pointer down by 0x10 bytes and thereby "allocates" those bytes for use by a variable.)
sub esp, 0x10
The OS (which is responsible for page faulting / swapping), and the hardware (CPU) trapping on accesses to swapped-out or not-yet-accessed pages, would not even be tracking which pages are "stack" vs "heap"... a memory page is a memory page
That said, the virtual address of global data may be able to be calculated and hardcoded at compile time,
The addresses of stack-based data are typically stack-pointer relative, while memory on the heap must almost always be accessed using pointers, which might be slightly slower on some systems -
it depends on the CPU addressing modes and cycles, but it's almost always insignificant -
not even worth a look or second thought unless you're writing something where millionths of a second are enormously important.
17.
Memory Allocation on Stack Vs Heap
http://stackoverflow.com/questions/2264969/why-is-memory-allocation-on-heap-much-slower-than-on-stack
Stack Allocation:
- Just a matter of changing the stack pointer
- Just one Instruction
EG: sub esp, 0x10 - moves stack pointer by 10 bytes.
- Stack Allocations are also scoped to a particular function.
- Stack uses Data Locality and Caches the TOP of stack
- TOP of Stack is ALMOST ALWAYS on Cache Line
- Stack Variables might also get stored in Registers
- Items on Stack CANNOT be removed out of order.
- So adding a new items just adds to the end of stack. Move one pointer in stack.
Heap Allocation:
- Allocating memory on the heap involves looking for a big enough block, splitting it, and managing the "book-keeping" that allows things like free() in a different order.
- On Heap, Elements can be removed OUT of ORDER. So tough to maintain as HOLES will
be in middle.
17b.
What and Where are Stack and Heap
http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap?lq=1
The stack is the memory set aside as scratch space for a thread of execution.
When a function is called, a block is reserved on the top of the stack for local variables and some bookkeeping data.
When that function returns, the block becomes unused and can be used the next time a function is called.
The stack is always reserved in a LIFO (last in first out) order; the most recently reserved block is always the next block to be freed.
This makes it really simple to keep track of the stack; freeing a block from the stack is nothing more than adjusting one pointer.
The heap is memory set aside for dynamic allocation.
Unlike the stack, there's no enforced pattern to the allocation and deallocation of blocks from the heap; you can allocate a block at any time and free it at any time.
This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time; there are many custom heap allocators available to tune heap performance for different usage patterns.
Each thread gets a stack, while there's typically only one heap for the application (although it isn't uncommon to have multiple heaps for different types of allocation).
To answer your questions directly:
Q: To what extent are they controlled by the OS or language runtime?
A: The OS allocates the stack for each system-level thread when the thread is created.
Typically the OS is called by the language runtime to allocate the heap for the application.
Q: What is their scope?
A: The stack is attached to a thread, so when the thread exits the stack is reclaimed.
The heap is typically allocated at application startup by the runtime, and is reclaimed when the application (technically process) exits.
Q: What determines the size of each of them?
A: The size of the stack is set when a thread is created.
The size of the heap is set on application startup, but can grow as space is needed (the allocator requests more memory from the operating system).
Q: What makes one faster?
A: The stack is faster because the access pattern makes it trivial to allocate and deallocate memory from it (a pointer/integer is simply incremented or decremented), while the heap has much more complex bookkeeping involved in an allocation or deallocation.
Also, each byte in the stack tends to be reused very frequently which means it tends to be mapped to the processor's cache, making it very fast.
Another performance hit for the heap is that the heap, being mostly a global resource, typically has to be multi-threading safe, i.e. each allocation and deallocation needs to be - typically - synchronized with "all" other heap accesses in the program.
18.
Boxing and Unboxing
http://stackoverflow.com/questions/2111857/why-do-we-need-boxing-and-unboxing-in-c
Language C#:
double e = 2.718281828459045;
object o = e; // box
int ee = (int)(double)o; //unbox
First we have to explicitly unbox the double ((double)o) and then cast that to an int
19.
Shadowing and Overriding
http://stackoverflow.com/questions/392721/difference-between-shadowing-and-overriding-in-c
class A
{
public int Foo(){ return 5;}
public virtual int Bar(){return 5;}
}
class B : A{
public new int Foo() { return 1;} //shadow
public override int Bar() {return 1;} //override
}
then when you call this:
A clA = new A();
B clB = new B();
Console.WriteLine(clA.Foo()); // output 5
Console.WriteLine(clA.Bar()); // output 5
Console.WriteLine(clB.Foo()); // output 1
Console.WriteLine(clB.Bar()); // output 1
//now let's cast B to an A class
Console.WriteLine(((A)clB).Foo()); // output 5 <<<--
Console.WriteLine(((A)clB).Bar()); // output 1
20.
Agile Model
http://istqbexamcertification.com/what-is-agile-model-advantages-disadvantages-and-when-to-use-it/
- Software is developed in incremental, rapid cycles. results in small incremental releases with each release building on previous functionality
- DIS ADV: In case of some software deliverables, especially the large ones, it is difficult to assess the effort required at the beginning of the software development life cycle.
21.
Types of Polymorphism
Run time - Overriding
Compile time - Over loading
22.
Compiler vs Interpretor
http://stackoverflow.com/questions/3996651/what-is-compiler-linker-loader
Compiler:
Takes a high level language and converts it into Machine Code
The machine code is put in memory for execution
Interpretor:
Take the high level language code and on the go put each line into memory for execution
Doesn't get converted into an intermediate machine code.
But it does it at the moment the program is run
Compiler characteristics:
spends a lot of time analyzing and processing the program
the resulting executable is some form of machine- specific binary code
the computer hardware interprets (executes) the resulting code
program execution is fast
Interpreter characteristics:
relatively little time is spent analyzing and processing the program
the resulting code is some sort of intermediate code
the resulting code is interpreted by another program
program execution is relatively slow
=====> COMPILATION PROCESS <======
|
|----> Input is Source file(.c)
|
V
+=================+
| |
| C Preprocessor |
| |
+=================+
|
| ---> Pure C file ( comd:cc -E <file.name> )
|
V
+=================+
| |
| Lexical Analyzer|
| |
+-----------------+
| |
| Syntax Analyzer |
| |
+-----------------+
| |
| Semantic Analize|
| |
+-----------------+
| |
| Pre Optimization|
| |
+-----------------+
| |
| Code generation |
| |
+-----------------+
| |
| Post Optimize |
| |
+=================+
|
|---> Assembly code (comd: cc -S <file.name> )
|
V
+=================+
| |
| Assembler |
| |
+=================+
|
|---> Object file (.obj) (comd: cc -c <file.name>)
|
V
+=================+
| Linker |
+=================+
|
|---> Executable (.Exe/a.out) (com:cc <file.name> )
|
V
Executable file(a.out)
|
|---> Put into Main Memory
|
+=================+
| Loader |
+=================+
23.
Recursion vs Iterative Approach
http://www.codeproject.com/Articles/21194/Iterative-vs-Recursive-Approaches
http://stackoverflow.com/questions/72209/recursion-or-iteration
It is possible that recursion will be more expensive, depending on if the recursive function is tail recursive (last line is recursive call).
Tail recursion should be recognized by the compiler and optimized to its iterative counterpart (while maintaining the concise, clear implementation you have in your code).
Basically, a recursive algorithm will add overhead since you store recursive calls in the execution stack.
But if the recursive function is the last line of the call (tail recursion) then there is no additional penalty.
That is of course both algorithms are the same
24.
Tail Recursion Advantages
http://stackoverflow.com/questions/19854007/what-is-the-advantage-of-using-tail-recursion-here
A tail recursive function call allows the compiler to perform a special optimization which it normally can not with regular recursion.
In a tail recursive function, the recursive call is the very last thing to be executed.
In this case, instead of allocating a stack frame for each call, the compiler can rework the code to simply reuse the current stack frame, meaning a tail-recursive function will only use a single stack frame as opposed to hundreds or even thousands.
Not tail recursive example:
// A NON-tail-recursive function. The function is not tail
// recursive because the value returned by fact(n-1) is used in
// fact(n) and call to fact(n-1) is not the last thing done by fact(n)
unsigned int fact(unsigned int n)
{
if (n == 0) return 1;
return n*fact(n-1);
}
Tail Recursive example:
// A tail recursive function to calculate factorial
unsigned factTR(unsigned int n, unsigned int a)
{
if (n == 0) return a;
return factTR(n-1, n*a);
}
// A wrapper over factTR
unsigned int fact(unsigned int n)
{
return factTR(n, 1);
}
25.
Problems with Multiple Inheritence
http://stackoverflow.com/questions/225929/what-is-the-exact-problem-with-multiple-inheritance
http://stackoverflow.com/questions/406081/why-should-i-avoid-multiple-inheritance-in-c
The most obvious problem is with function overriding.
Let's say have two classes A and B, both of which define a method "doSomething".
Now you define a third class C, which inherits from both A and B, but you don't override the "doSomething" method.
When the compiler seed this code...
C c = new C();