--- tags: interview, embedded software engineer --- # Preparation for Embedded Software Engineer ## Thread ### 解釋 process 與 thread 間的關係 ==A thread is a single sequential flow of control within a process.== When we use thread programming, we create multiple threads at the same time and use them to perform different tasks in a single process. A CPU is giving you the illusion that it's doing multiple computations at the same time. It does that by spending a bit of time on each computation. It can do that because it has an execution context for each computation. An execution context (therefore a thread) consists of the values of the CPU's registers. * An analogy Suppose you're reading a book, and you want to take a break right now, but you want to be able to come back and resume reading from the exact point where you stopped. One way to achieve that is by jotting down the page number, line number, and word number. So your execution context for reading a book is these 3 numbers. If you have a roommate, and she's using the same technique, she can take the book while you're not using it, and resume reading from where she stopped. Then you can take it back, and resume it from where you were. #### The difference between a trhead and a process threads are different from processes. A thread is a context of execution, while a process is a bunch of resources associated with a computation. A process can have one or many threads. The resources associated with a process include memory pages (all the threads in a process have the same view of the memory), file descriptors (e.g., open sockets), and security credentials (e.g., the ID of the user who started the process). #### process 與 thread 一併解釋 In order to define a thread formally, we must first understand the boundaries of where a thread operates. A computer program becomes a **process** when it is loaded from some store into the computer's memory and begins execution. A process can be executed by a processor or a set of processors. A process description in memory contains vital information such as the program counter which keeps track of the current position in the program (i.e. which instruction is currently being executed), registers, variable stores, file handles, signals, and so forth. A **thread** is a sequence of such instructions within a program that can be executed independently of other code. The figure shows the concept: ![](https://i.imgur.com/aXciUFl.png) **Threads are within the same process address space**, thus, much of the information present in the memory description of the process can be shared across threads. Some information cannot be replicated, such as the stack (stack pointer to a different memory area per thread), registers and thread-specific data. **This information suffices to allow threads to be scheduled independently** of the program's main thread and possibly one or more other threads within the program. * reference * [What Is a Thread?](https://www.iitk.ac.in/esc101/05Aug/tutorial/essential/threads/definition.html) * [What is a "thread" (really)?](https://stackoverflow.com/questions/5201852/what-is-a-thread-really) ### What's a thread? A thread is a distinct execution path or a subprocess. Within a process, you can have either a single thread or multiple threads sharing the same process resources. * reference: [24 Multithreading Interview Questions (With Example Answers)](https://www.indeed.com/career-advice/interviewing/multithreading-interview-questions) Threads are basically the lightweight and smallest unit of processing that can be managed independently by a scheduler. Threads are referred to as parts of a process that simply let a program execute efficiently with other parts or threads of the process at the same time. Using threads, one can perform complicated tasks in the easiest way. It is considered the simplest way to take advantage of multiple CPUs available in a machine. They share the common address space and are independent of each other. * reference: [What do you mean by Multithreading? Why is it important?](https://www.interviewbit.com/multithreading-interview-questions/#what-is-thread-in-java) ### What's multithreading? Multithreading is the ability to have multiple threads executing concurrently. While each thread shares the same process resources, they operate independently of each other. * reference: [24 Multithreading Interview Questions (With Example Answers)](https://www.indeed.com/career-advice/interviewing/multithreading-interview-questions) ### What's the difference between a thread and a process? A process is a single application or program, whereas a thread is a subprocess within that application or program. Each process has its own address space in memory. Threads share their address space. * reference: [24 Multithreading Interview Questions (With Example Answers)](https://www.indeed.com/career-advice/interviewing/multithreading-interview-questions) Thread: It simply refers to the smallest units of the particular process. It has the ability to execute different parts (referred to as thread) of the program at the same time. Process: It simply refers to a program that is in execution i.e., an active program. A process can be handled using PCB (Process Control Block). * reference: [What do you mean by Multithreading? Why is it important?](https://www.interviewbit.com/multithreading-interview-questions/#difference-between-thread-and-process) ### Why use multithreading in your applications? Since each thread runs concurrently, multithreading makes efficient use of the CPU. You can have background processes running while the application receives user input. Also, tasks can execute faster since each thread runs independently. * reference: [24 Multithreading Interview Questions (With Example Answers)](https://www.indeed.com/career-advice/interviewing/multithreading-interview-questions) There are various benefits of multithreading as given below: 1. Allow the program to run continuously even if a part of it is blocked. 1. Improve performance as compared to traditional parallel programs that use multiple processes. 1. Allows to write effective programs that utilize maximum CPU time 1. Improves the responsiveness of complex applications or programs. 1. Increase use of CPU resources and reduce costs of maintenance. 1. Saves time and parallelism tasks. 1. If an exception occurs in a single thread, it will not affect other threads as threads are independent. 1. Less resource-intensive than executing multiple processes at the same time. * reference: [What do you mean by Multithreading? Why is it important?](https://www.interviewbit.com/multithreading-interview-questions/#benefits-of-multithreading) <!-- ### What's a thread pool? A thread pool is a collection of worker threads created at start-up that programmers can assign tasks to as needed, then put back in the pool when complete. The main advantage of using a thread pool is having a supply of ready-made threads when you need them, which improves application performance. * reference: [24 Multithreading Interview Questions (With Example Answers)](https://www.indeed.com/career-advice/interviewing/multithreading-interview-questions) A Thread pool is simply a collection of pre-initialized or worker threads at the start-up that can be used to execute tasks and put back in the pool when completed. It is referred to as pool threads in which a group of fixed-size threads is created. By reducing the number of application threads and managing their lifecycle, one can mitigate the issue of performance using a thread pool. Using threads, performance can be enhanced and better system stability can occur. To create the thread pools, java.util.concurrent.Executors class usually provides factory methods. * reference: [What do you mean by Multithreading? Why is it important?](https://www.interviewbit.com/multithreading-interview-questions/#explain-thread-pool) --> <!-- ### During a thread's lifetime, what states can it have? There are five states a thread can have: New, Runnable, Running, Waited/Blocked and Dead/Terminated. * reference: [24 Multithreading Interview Questions (With Example Answers)](https://www.indeed.com/career-advice/interviewing/multithreading-interview-questions) --> ### What's a race condition? A race condition occurs when multiple concurrent threads compete to run first. If the thread that wins the race isn't the one that was supposed to run first, the code may exhibit unexpected behavior. You can resolve this problem with synchronization. * reference: [24 Multithreading Interview Questions (With Example Answers)](https://www.indeed.com/career-advice/interviewing/multithreading-interview-questions) ### What's synchronization? Synchronization forces threads to run one at a time to prevent a race condition or multiple threads trying to perform the same task. * reference: [24 Multithreading Interview Questions (With Example Answers)](https://www.indeed.com/career-advice/interviewing/multithreading-interview-questions) Synchronization is basically a process in java that enables a simple strategy for avoiding thread interference and memory consistency errors. This process makes sure that resource will be only used one thread at a time when one thread tries to access a shared resource. * reference: [What do you mean by Multithreading? Why is it important?](https://www.interviewbit.com/multithreading-interview-questions/#synchronization-process-and-its-uses) <!-- ### Why might you use synchronized block? Synchronized block allows you to designate a particular portion of a method as synchronized. That is, only a single thread is able to run until it completes, prioritizing that thread above others. * reference: [24 Multithreading Interview Questions (With Example Answers)](https://www.indeed.com/career-advice/interviewing/multithreading-interview-questions) --> ### What's a context switch? A context switch allows programmers to store the current state of a thread. A context switch is where the current state of a thread or process is stored so the execution of that thread can resume at a later time. This enables a single CPU to manage multiple threads or processes. * reference: [24 Multithreading Interview Questions (With Example Answers)](https://www.indeed.com/career-advice/interviewing/multithreading-interview-questions) ### Can you explain what the thread scheduler is and its relationship to thread priority? The thread scheduler is what allocates CPU time to threads and determines the order in which threads execute. * reference: [24 Multithreading Interview Questions (With Example Answers)](https://www.indeed.com/career-advice/interviewing/multithreading-interview-questions) ### What's time slicing? Time slicing is the process used by the thread scheduler to divide CPU time between the available active threads. * reference: [24 Multithreading Interview Questions (With Example Answers)](https://www.indeed.com/career-advice/interviewing/multithreading-interview-questions) Thread Scheduler: It is a component of JVM that is used to decide which thread will execute next if multiple threads are waiting to get the chance of execution. By looking at the priority assigned to each thread that is READY, the thread scheduler selects the next run to execute. To schedule the threads, it mainly uses two mechanisms: Preemptive Scheduling and Time slicing scheduling. Time Slicing: It is especially used to divide CPU time and allocate them to active threads. In this, each thread will get a predefined slice of time to execute. When the time expires, a particular thread has to wait till other threads get their chances to use their time in a round-robin fashion. Every running thread will get executed for a fixed time period. * reference: [What do you mean by Multithreading? Why is it important?](https://www.interviewbit.com/multithreading-interview-questions/#thread-scheduler-and-time-slicing) ### Why might you describe thread behavior as unpredictable? Because thread scheduling is determined by the CPU, different CPUs may give priority to different threads. This means there's a chance two CPUs might not run your threads in the same order, creating unpredictability in your code execution. * reference: [24 Multithreading Interview Questions (With Example Answers)](https://www.indeed.com/career-advice/interviewing/multithreading-interview-questions) We can say that thread behavior is unpredictable because the execution of Threads depends on Thread scheduler. One should remember that every thread scheduler has a different implementation on different platforms like Windows, Unix, etc. * reference: [Top 40 Multithreading Interview Questions and Answers (2022)](https://career.guru99.com/top-40-multithreading-interview-questions-and-answers/) ### Explain the busy spin technique and why you might use it. Bust spinning is a wait strategy that programmers might use to prevent CPU release. Busy spin is when you pause a thread by making it run an empty loop for a certain period. Unlike other methods like wait() or sleep(), a busy spin doesn't give up CPU control and therefore preserves CPU cache. * reference: [24 Multithreading Interview Questions (With Example Answers)](https://www.indeed.com/career-advice/interviewing/multithreading-interview-questions) Busy Spinning, also known as Busy-waiting, is a technique in which one thread waits for some condition to happen, without calling wait or sleep methods and releasing the CPU. In this condition, one can pause a thread by making it run an empty loop for a certain time period, and it does not even give CPY control. Therefore, it is used to preserve CPU caches and avoid the cost of rebuilding cache. * reference: [https://www.interviewbit.com/multithreading-interview-questions/#what-is-busy-spinning](https://www.interviewbit.com/multithreading-interview-questions/#what-is-busy-spinning) ### What's thread starvation? Thread starvation is a phenomenon in which a given thread is unable to make progress due to a lack of resources. Thread starvation is when there's insufficient CPU capacity to execute a thread. This can happen with low-priority threads or threads that programmers demote in favor of other threads. * reference: [24 Multithreading Interview Questions (With Example Answers)](https://www.indeed.com/career-advice/interviewing/multithreading-interview-questions) Thread starvation is basically a situation or condition where a thread won’t be able to have regular access to shared resources and therefore is unable to proceed or make progress. This is because other threads have high priority and occupy the resources for too long. This usually happens with low-priority threads that do not get CPU for its execution to carry on. * reference: [What do you mean by Multithreading? Why is it important?](https://www.interviewbit.com/multithreading-interview-questions/#thread-starvation) <!-- ### Can you start a thread twice? Threads move through several different states during their lifecycle. Once you execute a thread, it's dead and you can't restart it * reference: [24 Multithreading Interview Questions (With Example Answers)](https://www.indeed.com/career-advice/interviewing/multithreading-interview-questions) --> ### Can you describe a deadlock situation? Deadlock is a common problem that can cause code to stall. A deadlock situation occurs when multiple threads are waiting on one another to release CPU resources so they can run. For example, this can happen when a single thread has exclusive priority but needs resources from a waiting thread, or all the threads are depending on one another to release needed resources. * reference: [24 Multithreading Interview Questions (With Example Answers)](https://www.indeed.com/career-advice/interviewing/multithreading-interview-questions) Deadlock, as the name suggests, is a situation where multiple threads are blocked forever. It generally occurs when multiple threads hold locks on different resources and are waiting for other resources to complete their task. ![](https://i.imgur.com/yRW0tzq.png) The above diagram shows a deadlock situation where two threads are blocked forever. Thread 1 is holding Object 1 but needs object 2 to complete processing whereas Thread 2 is holding Object 2 but needs object 1 first. In such conditions, both of them will hold lock forever and will never complete tasks * reference: [What do you mean by Multithreading? Why is it important?](https://www.interviewbit.com/multithreading-interview-questions/#what-is-deadlock-and-when-can-it-occur) Deadlock is a situation when a thread is waiting for an object lock, that is acquired by another thread and second thread also waiting for an object lock that is acquired by the first thread. As both threads are waiting for each other to release this condition is called deadlock. * reference: [Top 40 Multithreading Interview Questions and Answers (2022)](https://career.guru99.com/top-40-multithreading-interview-questions-and-answers/) ### What happens when a livelock occurs? A livelock is similar to a deadlock situation, except in a livelock, the state of the threads change without ever making progress. For instance, if all the threads are in infinite loops. * reference: [24 Multithreading Interview Questions (With Example Answers)](https://www.indeed.com/career-advice/interviewing/multithreading-interview-questions) Similar to deadlock, livelock is also another concurrency problem. In this case, the state of threads changes between one another without making any progress. Threads are not blocked but their execution is stopped due to the unavailability of resources. * reference: [What do you mean by Multithreading? Why is it important?](https://www.interviewbit.com/multithreading-interview-questions/#what-happens-when-a-livelock-occurs) Livelock occurs when all threads are blocked and not able to execute because of the unavailability of required resources, and non-existence of any unblocked thread. Livelock can occur in the following conditions: 1. When all the threads in a program executed on an object with zero parameters. The program is live-locked and never processed until one or more threads call Object.notify () or Object.notifyAll() on the relevant objects. 1. Livelock also happens when all the threads in a program are stuck in infinite loops. * reference: [Top 40 Multithreading Interview Questions and Answers (2022)](https://career.guru99.com/top-40-multithreading-interview-questions-and-answers/) <!-- ### In Java, what's the difference between the wait() and sleep() methods? The wait() method pauses a thread and waits until there are no notify() or notifyAll() method calls from other threads. The sleep() method pauses for a given period, allowing other threads to run, after which it resumes execution. * reference: [24 Multithreading Interview Questions (With Example Answers)](https://www.indeed.com/career-advice/interviewing/multithreading-interview-questions) --> <!-- ### What's a daemon thread? A daemon thread is a low-priority thread. It may provide background services or support to the other threads. When those threads die, the daemon thread automatically terminates. * reference: [24 Multithreading Interview Questions (With Example Answers)](https://www.indeed.com/career-advice/interviewing/multithreading-interview-questions) --> <!-- ### How might you achieve thread safety? Thread safety is an important concept since it prevents your code from hanging or crashing. You can achieve thread safety through several techniques, including synchronization, using the Volatile keyword or using atomic wrapper classes. * reference: [24 Multithreading Interview Questions (With Example Answers)](https://www.indeed.com/career-advice/interviewing/multithreading-interview-questions) --> ### What's the difference between synchronous and asynchronous programming? Synchronous programming runs tasks individually from a queue. Asynchronous programming allows multiple tasks to run at once on the same thread. * reference: [24 Multithreading Interview Questions (With Example Answers)](https://www.indeed.com/career-advice/interviewing/multithreading-interview-questions) ### Explain context switching. Context switching is basically an important feature of multithreading. It is referred to as switching of CPU from one thread or process to another one. It allows multiple processes to share the same CPU. In context switching, the state of thread or process is stored so that the execution of the thread can be resumed later if required. * reference: [What do you mean by Multithreading? Why is it important?](https://www.interviewbit.com/multithreading-interview-questions/#explain-context-switching) ### What is semaphore? Semaphore is regarded as a thread synchronization construct that is usually required to control and manage the access to the shared resource using counters. It simply sets the limit of the thread. The semaphore class is defined within the package java.util.concurrent and can be used to send signals between threads to avoid missed signals or to guard critical sections. It can also be used to implement resource pools or bounded collection. * reference: [What do you mean by Multithreading? Why is it important?](https://www.interviewbit.com/multithreading-interview-questions/#what-is-semaphore) ### Is it possible that each thread can have its stack in multithreaded programming? Of course, it is possible. In multithreaded programming, each thread maintains its own separate stack area in memory because of which every thread is independent of each other rather than dependent. * reference: [What do you mean by Multithreading? Why is it important?](https://www.interviewbit.com/multithreading-interview-questions/#what-is-semaphore) ### Can we write multithreading programs in C? Multithreading is not supported by the language standard. POSIX Threads (or Pthreads) is a POSIX standard for threads. Implementation of pthread is available with gcc compiler. * reference: [Multithreading in C](https://www.geeksforgeeks.org/multithreading-c-2/) ### How do you create a thread in C? A simple C program to demonstrate use of pthread basic functions Please note that the below program may compile only with C compilers with pthread library. ```c #include <stdio.h> #include <stdlib.h> #include <unistd.h> //Header file for sleep(). man 3 sleep for details. #include <pthread.h> // A normal C function that is executed as a thread // when its name is specified in pthread_create() void *myThreadFun(void *vargp) { sleep(1); printf("Printing GeeksQuiz from Thread \n"); return NULL; } int main() { pthread_t thread_id; printf("Before Thread\n"); pthread_create(&thread_id, NULL, myThreadFun, NULL); pthread_join(thread_id, NULL); printf("After Thread\n"); exit(0); } ``` In main(), we declare a variable called thread_id, which is of type pthread_t, which is an integer used to identify the thread in the system. After declaring thread_id, we call pthread_create() function to create a thread. pthread_create() takes 4 arguments. The first argument is a pointer to thread_id which is set by this function. The second argument specifies attributes. If the value is NULL, then default attributes shall be used. The third argument is name of function to be executed for the thread to be created. The fourth argument is used to pass arguments to the function, myThreadFun. The pthread_join() function for threads is the equivalent of wait() for processes. A call to pthread_join blocks the calling thread until the thread with identifier equal to the first argument terminates. #### How to compile a multi-thread program in C? To compile a multithreaded program using gcc, we need to link it with the pthreads library. Following is the command used to compile the program. ```console gfg@ubuntu:~/$ gcc multithread.c -lpthread gfg@ubuntu:~/$ ./a.out Before Thread Printing GeeksQuiz from Thread After Thread gfg@ubuntu:~/$ ``` #### A C program to show multiple threads with global and static variables As mentioned above, all threads share data segment. Global and static variables are stored in data segment. Therefore, they are shared by all threads. The following example program demonstrates the same. ```c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> // Let us create a global variable to change it in threads int g = 0; // The function to be executed by all threads void *myThreadFun(void *vargp) { // Store the value argument passed to this thread int *myid = (int *)vargp; // Let us create a static variable to observe its changes static int s = 0; // Change static and global variables ++s; ++g; // Print the argument, static and global variables printf("Thread ID: %d, Static: %d, Global: %d\n", *myid, ++s, ++g); } int main() { int i; pthread_t tid; // Let us create three threads for (i = 0; i < 3; i++) pthread_create(&tid, NULL, myThreadFun, (void *)&tid); pthread_exit(NULL); return 0; } ``` ```console gfg@ubuntu:~/$ gcc multithread.c -lpthread gfg@ubuntu:~/$ ./a.out Thread ID: 3, Static: 2, Global: 2 Thread ID: 3, Static: 4, Global: 4 Thread ID: 3, Static: 6, Global: 6 gfg@ubuntu:~/$ ``` Please note that above is simple example to show how threads work. Accessing a global variable in a thread is generally a bad idea. What if thread 2 has priority over thread 1 and thread 1 needs to change the variable. In practice, if it is required to access global variable by multiple threads, then they should be accessed using a mutex. * reference: [POSIX Threads](http://www.csc.villanova.edu/~mdamian/threads/posixthreads.html) [Multithreading in C](https://www.geeksforgeeks.org/multithreading-c-2/) [Multithreading in C++](https://www.geeksforgeeks.org/multithreading-in-cpp/?ref=lbp) [C++ Multithreading](https://www.tutorialspoint.com/cplusplus/cpp_multithreading.htm) ### How can you implement synchronization in C/C++? ### How can you pause the execution of a Thread for a certain amount of time? ### How can you share data between two thread in C? ### What’s the purpose of the join() method? ### How do threads communicate with each other? ### How do processes communicate with each other? ## C language ### What do you understand by startup code? A startup code is that piece of code that is called before the execution of the main function. This is used for creating a basic platform for the application and it is written in assembly language. [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#startup-code) ### Why do we use the `volatile` keyword? The `volatile` keyword is mainly used for preventing a compiler from optimizing a variable that might change its behaviour unexpectedly post the optimization. Consider a scenario where we have a variable where there is a possibility of its value getting updated by some event or a signal, then we need to tell the compiler not to optimize it and load that variable every time it is called. To inform the compiler, we use the keyword volatile at the time of variable declaration. ```c // Declaring volatile variable - SYNTAX // volatile datatype variable_name; volatile int x; ``` Here, x is an integer variable that is defined as a volatile variable. [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#why-do-we-use-volatile-keyword) ### What are the differences between the `const` and `volatile` qualifiers in embedded C? The keyword `const` is enforced by the compiler and tells it that no changes can be made to the value of that object/variable during program execution. Example: `const int x=20;`, here if the program attempts to modify the value of x, then there would be a compiler error as there is const keyword assigned which makes the variable x non-modifiable. The keyword `volatile` tells the compiler to not perform any optimization on the variables and not to assume anything about the variables against which it is declared. Example: `volatile int x;`, here the compiler is told to not assume anything regarding the variable x and avoid performing optimizations on it. Every time the compiler encounters the variable, fetch it from the memory it is assigned to. [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#difference-between-const-and-volatile-qualifiers) ### Is it possible for a variable to be both volatile and const? The const keyword is used when we want to ensure that the variable value should not be changed. However, the value can still be changed due to external interrupts or events. So, we can use const with volatile keywords and it won’t cause any problem. [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#is-it-possible-for-a-variable-to-be-both-volatile-and-const) ### What Is Concatenation Operator in Embedded C? The Concatenation operator is indicated by the usage of ##. It is used in macros to perform concatenation of the arguments in the macro. We need to keep note that only the arguments are concatenated, not the values of those arguments. For example, if we have the following piece of code: ```c #define CUSTOM_MACRO(x, y) x##y main(){ int xValue = 20; printf(“%d”, CUSTOM_MACRO(x, Value)); //Prints 20 } ``` We can think of it like this if arguments `x` and `y` are passed, then the macro just returns `xy` -> The concatenation of `x` and `y` [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#concatenation-operator-in-embedded-c) ### `static` in C ### `static` in C++ ### Is it possible to declare a static variable in a header file? Variables defined with static are initialized once and persists until the end of the program and are local only to the block it is defined. A static variables declaration requires definition. It can be defined in a header file. But if we do so, a private copy of the variable of the header file will be present in each source file the header is included. This is not preferred and hence it is not recommended to use static variables in a header file. [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#is-it-possible-to-declare-static-variable-in-header-file) ### pointer, function pointer, callback function ### Is it possible to protect a character pointer from accidentally pointing it to a different address? It can be done by defining it as a constant character pointer. const protects it from modifications. [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#is-it-possible-to-protect-a-character-pointer-from-accidentally-pointing-it-to-different-address) ### What do you understand by Wild Pointer? How is it different from Dangling Pointer? A pointer is said to be a wild pointer if it has not been initialized to NULL or a valid memory address. Consider the following declaration: ```c int *ptr; *ptr = 20; ``` Here the pointer ptr is not initialized and in the next step, we are trying to assign a valid value to it. If the ptr has a garbage location address, then that would corrupt the upcoming instructions too. If we are trying to de-allocate this pointer and free it as well using the free function, and again if we are not assigning the pointer as NULL or any valid address, then again chances are that the pointer would still be pointing to the garbage location and accessing from that would lead to errors. These pointers are called dangling pointers. [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#what-is-wild-pointer-how-is-it-different-from-dangling-pointer) ### What is Void Pointer in Embedded C and why is it used? Void pointers are those pointers that point to a variable of any type. It is a generic pointer as it is not dependent on any of the inbuilt or user-defined data types while referencing. During dereferencing of the pointer, we require the correct data type to which the data needs to be dereferenced. For Example: ```c int num1 = 20; //variable of int datatype void *ptr; //Void Pointer *ptr = &num1; //Point the pointer to int data print("%d",(*(int*)ptr)); //Dereferencing requires specific data type char c = 'a'; *ptr = &c; //Same void pointer can be used to point to data of different type -> reusability print("%c",(*(char*)ptr)); ``` Void pointers are used mainly because of their nature of re-usability. It is reusable because any type of data can be stored. [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#void-pointer) ### What do you understand by a null pointer in Embedded C? A null pointer is a pointer that does not point to any valid memory location. It is defined to ensure that the pointer should not be used to modify anything as it is invalid. If no address is assigned to the pointer, it is set to `NULL`. Syntax: ```c data_type *pointer_name = NULL; ``` One of the uses of the null pointer is that once the memory allocated to a pointer is freed up, we will be using NULL to assign to the pointer so that it does not point to any garbage locations. [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#null-pointer) ### When does a memory leak occur? What are the ways of avoiding it? Memory leak is a phenomenon that occurs when the developers create objects or make use of memory to help memory and then forget to free the memory before the completion of the program. This results in reduced system performance due to the reduced memory availability and if this continues, at one point, the application can crash. These are serious issues for applications involving servers, daemons, etc that should ideally never terminate. Example of Memory Leak: ```c #include <stdlib.h> void memLeakDemo() { int *p = (int *) malloc(sizeof(int)); /* Some set of statements */ return; /* Return from the function without freeing the pointer p*/ } ``` In this example, we have created pointer p inside the function and we have not freed the pointer before the completion of the function. This causes pointer p to remain in the memory. Imagine 100s of pointers like these. The memory will be occupied unnecessarily and hence resulting in a memory leak. We can avoid memory leaks by always freeing the objects and pointers when no longer required. The above example can be modified as: ```c #include <stdlib.h>; void memLeakFix() { int *p = (int *) malloc(sizeof(int)); /* Some set of statements */ free(p); // Free method to free the memory allocated to the pointer p return; } ``` [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#when-does-memory-leak-occur-ways-to-avoid-it) ### What are the differences between the following 2 statements #include "..." and #include <...>? Both declarations specify for the files to be included in the current source file. The difference is in how and where the preprocessor looks for including the files. For `#include "..."`, the preprocessor just searches for the file in the current directory as where the source file is present and if not found, it proceeds to search in the standard directories specified by the compiler. Whereas for the `#include <...>` declaration, the preprocessor looks for the files in the compiler designated directories where the standard library files usually reside. [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#difference-between-include-and-include) ### Write an Embedded C program to multiply any number by 9 in the fastest manner. ```c #include<stdio.h> void main(){ int num; printf(“Enter number: ”); scanf(“%d”,&num); printf(“%d”, (num<<3)+num); } ``` [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#program-to-multiply-any-number-by-9-in-the-fastest-manner) ### How will you swap two variables? Write different approaches for the same. * Using Extra Memory Space: ```c int num1=20, num2=30, temp; temp = num1; num1 = num2; num2 = temp; ``` * Using Arithmetic Operators: ```c int num1=20, num2=30; num1=num1 + num2; num2=num1 - num2; num1=num1 - num2; ``` * Using Bit-Wise Operators: ```c int num1=20, num2=30; num1=num1 ^ num2; num2=num2 ^ num1; num1=num1 ^ num2; ``` * Using One-liner Bit-wise Operators: ```c int num1=20, num2=30; num1^=num2^=num1^=num2; ``` The order of evaluation here is right to left. * Using One-liner Arithmetic Operators: ``` int num1=20, num2=30; num1 = (num1+num2)-(num2=num1); ``` Here the order of evaluation is from left to right. [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#different-approaches-to-swap-two-variables) ### Write a program to check if a number is a power of 2 or not. We can do this by using bitwise operators. ```c void main (){ int num; printf ("Enter any no:"); scanf ("%d", &num); if (num & & ((num & num-1) == 0)) printf ("Number is a power of 2"); else printf ("Number is not a power of 2"); } ``` [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#program-to-check-if-number-is-a-power-of-2-or-not) ### Write a program to print numbers from 1 to 100 without making use of conditional operators? ```c void main (){ int i=0; while (100 – i++) printf ("%d", i); } ``` [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#program-to-print-numbers-from-1-to-100-without-making-use-of-conditional-operators) <!-- ### Write a MIN macro program that takes two arguments and returns the smallest of both arguments. ```c #define MIN(NUM1,NUM2) ( (NUM1) <= (NUM2) ? (NUM1) : (NUM2) ) ``` [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#write-a-min-macro-program-takes-two-arguments-and-returns-the-smallest-of-both-arguments) --> <!-- ### How will you use a variable defined in source file1 inside source file2? We can achieve this by making use of the “extern” keyboard. It allows the variable to be accessible from one file to another. This can be handled more cleanly by creating a header file that just consists of extern variable declarations. This header file is then included in the source files which uses the extern variables. Consider an example where we have a header file named `variables.h` and a source file named `sc_file.c`. ```c /* variables.h*/ extern int global_variable_x; ``` ```c /* sc_file.c*/ #include "variables.h" /* Header variables included */ #include <stdio.h> void demoFunction(void) { printf("Value of Global Variable X: %d\n", global_variable_x++); } ``` [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#how-will-use-a-variable-defined-in-source-file1-inside-source-file2) --> ### What do you understand by segmentation fault? A segmentation fault occurs most commonly and often leads to crashes in the programs. It occurs when a program instruction tries to access a memory address that is prohibited from getting accessed. [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#segmentation-fault) ### What are the reasons for segmentation fault in Embedded C? How do you avoid these errors? Following are the reasons for the segmentation fault to occur: * While trying to dereference NULL pointers. * While trying to write or update the read-only memory or non-existent memory not accessible by the program such as code segment, kernel structures, etc. * While trying to dereference an uninitialized pointer that might have been pointing to invalid memory. * While trying to dereference a pointer that was recently freed using the free function. * While accessing the array beyond the boundary. Some of the ways where we can avoid Segmentation fault are: * Initializing Pointer Properly: Assign addresses to the pointers properly. For instance: * We can also assign the address of the matrix, vectors or using functions like calloc, malloc etc. * Only important thing is to assign value to the pointer before accessing it. ```c int varName; int *p = &varName; ``` * Minimize using pointers: Most of the functions in Embedded C such as scanf, require that address should be sent as a parameter to them. In cases like these, as best practices, we declare a variable and send the address of that variable to that function as shown below: ```c int x; scanf("%d",&x); ``` In the same way, while sending the address of variables to custom-defined functions, we can use the & parameter instead of using pointer variables to access the address. ```c int x = 1; x = customFunction(&x); ``` * Troubleshooting: Make sure that every component of the program like pointers, array subscripts, & operator, * operator, array accessing, etc as they can be likely candidates for segmentation error. Debug the statements line by line to identify the line that causes the error and investigate them. [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#reasons-for-segmentation-fault-to-occur-how-to-avoid-it) ### What are the differences between Inline and Macro Function? | Category | Macro Function | Inline Function | | ---------------------- | ----------------------------------------------------------------------------- | ---------------------------------------------- | | Compile-time expansion | Macro functions are expanded by the preprocessor at the compile time. | Inline functions are expanded by the compiler. | | Argument Evaluation | Expressions passed to the Macro functions might get evaluated more than once. | Expressions passed to Inline functions get evaluated once. | | Parameter Checking | Macro functions do not follow strict parameter data type checking. | Inline functions follow strict data type checking of the parameters. | | Ease of debugging | Macro functions are hard to debug because it is replaced by the pre-processor as a textual representation which is not visible in the source code. | Easier to debug inline functions which is why it is recommended to be used over macro functions. | | Example | `#define SQUARENUM(A) A * A` -> The macro functions are expanded at compile time. Hence, if we pass, the output will be evaluated to 3+2*3+2 which gets evaluated to 11. This might not be as per our expectations. | `inline squareNum(int A){return A * A;}` -> If we have printf(squareNum(3+2));, the arguments to the function are evaluated first to 5 and passed to the function, which returns a square of 5 = 25. | [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#differences-between-inline-and-macro-function) <!-- ### What do you understand by the pre-decrement and post-decrement operators? The Pre-decrement operator ( `--operand` ) is used for decrementing the value of the variable by 1 before assigning the variable value. ```c #include < stdio.h > int main(){ int x = 100, y; y = --x; //pre-decrememt operators -- first decrements the value and then it is assigned printf("y = %d\n", y); // Prints 99 printf("x = %d\n", x); // Prints 99 return 0; } ``` The Post-decrement operator ( `operand--` ) is used for decrementing the value of a variable by 1 after assigning the variable value. ```c #include < stdio.h > int main(){ int x = 100, y; y = x--; //post-decrememt operators -- first assigns the value and then it is decremented printf("y = %d\n", y); // Prints 100 printf("x = %d\n", x); // Prints 99 return 0; } ``` --> [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#pre-decrement-and-post-decrement-operators) ### What is a reentrant function? A function is called reentrant if the function can be interrupted in the middle of the execution and be safely called again (re-entered) to complete the execution. The interruption can be in the form of external events or signals or internal signals like call or jump. The reentrant function resumes at the point where the execution was left off and proceeds to completion. [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#reentrant-function) ### What is ISR? ISR expands to Interrupt Service Routines. These are the procedures stored at a particular memory location and are called when certain interrupts occur. Interrupt refers to the signal sent to the processor that indicates there is a high-priority event that requires immediate attention. The processor suspends the normal flow of the program, executes the instructions in ISR to cater for the high priority event. Post execution of the ISR, the normal flow of the program resumes. The following diagrams represent the flow of ISR. ![](https://i.imgur.com/EdEQwhP.jpg) [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#interrupt-service-routines) ### Is it recommended to use printf() inside ISR? printf() is a non-reentrant and thread-safe function which is why it is not recommended to call inside the ISR. [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#is-it-recommended-to-use-printf-inside-isr) <!-- ### Is it possible to pass a parameter to ISR or return a value from it? An ISR by nature does not allow anything to pass nor does it return anything. This is because ISR is a routine called whenever hardware or software events occur and is not in control of the code. [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#is-it-possible-to-pass-a-parameter-to-isr-or-return-value-from-it) --> <!-- ### What kind of loop is better - Count up from zero or Count Down to zero? Loops that involve count down to zero are better than count-up loops. This is because the compiler can optimize the comparison to zero at the time of loop termination. The processors need not have to load both the loop variable and the maximum value for comparison due to the optimization. Hence, count down to 0 loops are always better. [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#which-loop-is-better-count-up-from-zero-or-count-down-to-zero) --> <!-- ``### What Is a Virtual Memory in Embedded C and how can it be implemented? Virtual memory is a means of allocating memory to the processes if there is a shortage of physical memory by using an automatic allocation of storage. The main advantage of using virtual memory is that it is possible to have larger virtual memory than physical memory. It can be implemented by using the technique of paging. Paging works as follows: * Whenever a process needs to be executed, it would be swapped into the memory by using a lazy swapper called a pager. * The pager tries to guess which page needs to get access to the memory based on a predefined algorithm and swaps that process. This ensures that the whole process is not swapped into the memory, but only the necessary parts of the process are swapped utilizing pages. * This decreases the time taken to swap and unnecessary reading of memory pages and reduces the physical memory required. [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#what-is-virtual-memory-how-can-it-be-implemented) --> <!-- ### Following are some incomplete declarations, what do each of them mean? ```c 1. const int x; 2. int const x; 3. const int *x; 4. int * const x; 5. int const * x const; ``` * The first two declaration points 1 and 2 mean the same. It means that the variable x is a read-only constant integer. * The third declaration represents that the variable a is a pointer to a constant integer. The integer value can't be modified but the pointer can be modified to point to other locations. * The fourth declaration means that the variable x is a constant pointer to an integer value. It means that the integer value can be changed, but the pointer can't be made to point to anything else. * The last declaration means that the variable x is a constant pointer to a constant integer which means that neither the pointer can point to a different location nor the integer value can be modified. [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#what-do-each-of-the-incomplete-declarations-mean) <!-- ### Why is the statement ++i faster than i+1? * ++i instruction uses single machine instruction like INR (Increment Register) to perform the increment. * For the instruction i+1, it requires to load the value of the variable i and then perform the INR operation on it. Due to the additional load, ++i is faster than the i+1 instruction. [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#why-statement-i-faster-than-i-1) --> <!-- ### What is the issue with the following piece of code? ```c int square (volatile int *p){ return (*p) * (*p) ; } ``` From the code given, it appears that the function intends to return the square of the values pointed by the pointer p. But, since we have the pointer point to a volatile integer, the compiler generates code as below: ```c int square ( volatile int *p){ int x , y; x = *p ; y = *p ; return x * y ; } ``` Since the pointer can be changed to point to other locations, it might be possible that the values of the x and y would be different which might not even result in the square of the numbers. Hence, the correct way for achieving the square of the number is by coding as below: ```c long square (volatile int *p ){ int x ; x = *p ; return x*x; } ``` [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#what-is-the-issue-with-following-piece-of-code) --> <!-- ### The following piece of code uses __interrupt keyword to define an ISR. Comment on the correctness of the code. ```c __interrupt double calculate_circle_area (double radius){ double circle_area = PI ∗ radius ∗ radius; printf ( 'Area = %f ' , circle_area); return circle_area; } ``` Following things are wrong with the given piece of code: * ISRs are not supposed to return any value. The given code returns a value of datatype double. * It is not possible to pass parameters to ISRs. Here, we are passing a parameter to the ISR which is wrong. * It is not advisable to have printf inside the ISR as they are non-reentrant and thereby it impacts the performance. --> <!-- ### What is the result of the below code? ```c void demo(void){ unsigned int x = 10 ; int y = −40; if(x + y > 10) { printf("Greater than 10"); } else { printf("Less than or equals 10"); } } ``` In Embedded C, we need to know a fact that when expressions are having signed and unsigned operand types, then every operand will be promoted to an unsigned type. Herem the -40 will be promoted to unsigned type thereby making it a very large value when compared to 10. Hence, we will get the statement “Greater than 10” printed on the console. [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#what-is-the-result-of-the-code) --> ## Hardware Related Knowledge ### What is DMA? ### What is interrupt? ### What do you understand by Interrupt Latency? Interrupt latency refers to the time taken by ISR to respond to the interrupt. The lesser the latency faster is the response to the interrupt event. ![](https://i.imgur.com/gKCpQT2.jpg) [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#interrupt-latency) ### What are the reasons for Interrupt Latency and how to reduce it? Following are the various causes of Interrupt Latency: * Hardware: Whenever an interrupt occurs, the signal has to be synchronized with the CPU clock cycles. Depending on the hardware of the processor and the logic of synchronization, it can take up to 3 CPU cycles before the interrupt signal has reached the processor for processing. * Pipeline: Most of the modern CPUs have instructions pipelined. Execution happens when the instruction has reached the last stage of the pipeline. Once the execution of an instruction is done, it would require some extra CPU cycles to refill the pipeline with instructions. This contributes to the latency. Interrupt latency can be reduced by ensuring that the ISR routines are short. When a lower priority interrupt gets triggered while a higher priority interrupt is getting executed, then the lower priority interrupt would get delayed resulting in increased latency. In such cases, having smaller ISR routines for lower priority interrupts would help to reduce the delay. Also, better scheduling and synchronization algorithms in the processor CPU would help minimize the ISR latency. [Embedded C Interview Questions](https://www.interviewbit.com/embedded-c-interview-questions/#reasons-for-interrupt-latency-how-to-reduce-it) ### What is I2C? [BASICS OF THE I2C COMMUNICATION PROTOCOL](https://www.circuitbasics.com/basics-of-the-i2c-communication-protocol/) ### What is GPIO? ### What is UART? [UART: A Hardware Communication Protocol Understanding Universal Asynchronous Receiver/Transmitter](https://www.analog.com/en/analog-dialogue/articles/uart-a-hardware-communication-protocol.html) ### What is SGPIO? ### What is memory mapping IO? Memory-mapped I/O uses the same address space to address both main memory and I/O devices. The memory and registers of the I/O devices are mapped to (associated with) address values. So a memory address may refer to either a portion of physical RAM, or instead to memory and registers of the I/O device. Thus, the CPU instructions used to access the memory can also be used for accessing devices. * [Memory-mapped I/O](https://en.wikipedia.org/wiki/Memory-mapped_I/O) Memory mapped I/O is a way to exchange data and instructions between a CPU and peripheral devices attached to it. Memory mapped IO is one where the processor and the IO device share the same memory location(memory),i.e.,the processor and IO devices are mapped using the memory address. Memory-mapped I/O uses the same address bus to address both memory and I/O devices, and the CPU instructions used are same for accessing the memory and also accessing devices ### What is watchdog? A watchdog timer (WDT) is a timer that monitors microcontroller (MCU) programs to see if they are out of control or have stopped operating. It acts as a “watchdog” watching over MCU operation. The watchdog timer communicates with the MCU at a set interval. If the MCU does not output a signal, outputs too many signals or outputs signals that differ from a predetermined pattern, the timer determines that the MCU is malfunctioning and sends a reset signal to the MCU. The WDT uses a number of methods (modes) to detect MCU faults and the type of faults it detects varies with the mode.The following is a description of WDT operation and features by mode. * Time-out mode In this mode, the watchdog timer determines the MCU is malfunctioning and outputs a reset signal if it does not receive a signal from the MCU within the set interval. The time-out mode is a major WDT monitoring mode or method, but it sometimes fails to detect MCU faults. In Time-out mode, the WDT will not detect an MCU fault if the MCU inputs multiple signals (= double pulse) in the set period. * Window mode The window mode enables more accurate detection of faults than the Time-out mode. In window mode, the watchdog timer determines that the MCU is malfunctioning and outputs a reset signal if it does not receive a signal, or receives multiple signals (= double pulse) from the MCU within the set interval. A window mode watchdog timer may be more suitable for applications such as automotive devices that require greater safety. * Q&A (Question & Answer) mode The Q&A mode enables more accurate detection of faults than the previous two modes. In Q&A mode, the MCU sends predetermined data to the WDT. The WDT determines whether or not the MCU is operating normally depending on whether or not the signal sent by the MCU matches predetermined data. Devices that require a high degree of safety, may require a Q&A mode WDT. However, unlike the window and the timeout modes, this mode relies on data communication between the MCU and WDT, which makes operation more complex. [What is a watchdog timer (WDT)?](https://www.ablic.com/en/semicon/products/automotive/automotive-watchdog-timer/intro/) ### What is timer? [Top Embedded Software Engineer Interview Questions You Should Learn](https://www.interviewkickstart.com/interview-questions/embedded-software-engineer-interview-questions) [Qualcomm Interview Question for Software Engineer / Developers](https://www.careercup.com/question?id=183830) [嵌入式筆試面試題目系列(彙總)](https://tw511.com/a/01/26758.html) [Top 40+ Most Asked Embedded C Interview Question and Answers](https://www.javatpoint.com/embedded-c-interview-questions) [Top Embedded Systems Interview Questions for 2023](https://www.simplilearn.com/embedded-systems-interview-questions-answers-article) [10 Essential Embedded Software Engineering Interview Questions](https://www.toptal.com/embedded/interview-questions) [35 Embedded Engineer Interview Questions And Sample Answers](https://in.indeed.com/career-advice/interviewing/embedded-engineer-interview-questions) [Top 18 Embedded Systems Interview Questions and Answers](https://www.guru99.com/embedded-systems-interview-questions.html) [Interview Questions to Ask a Embedded Software Engineer| Xobin [Downloaded]](https://f.hubspotusercontent10.net/hubfs/7752519/InterviewGlossary/Interview_Questions_to_Ask_a_Embedded_Software_Engineer_Xobin_Downloaded.pdf) [[心得] google embedded SWE 面試心得](https://www.ptt.cc/bbs/Soft_Job/M.1613548617.A.C70.html) [10501 資訊工程學系 作業系統](https://ocw.nthu.edu.tw/ocw/index.php?page=course&cid=141) [嵌入式作業系統 Embedded Operating Systems](http://ocw.nctu.edu.tw/course_detail-v.php?bgid=8&gid=0&nid=575)