Baidu didn't ask me about my project, and tortured me all the way, which really hurts my heart!

Hello everyone, I am programmer Xiaohui.

Today, I will share a classmate’s face-to-face interview with Baidu’s internship. The technology stack is C++. Since the project has no bright spots, most of the content is about C++ questions, and there are not many project questions.

operating system

Understanding of new and malloc

Both new and malloc are dynamic memory allocation functions. Among them, new is an operator in C++, and malloc is a function in C language. new will call the object's constructor, but malloc will not. Using new simplifies the code and is more type safe.

Replenish:

The difference between new and malloc:

  • Where to allocate memory : malloc dynamically allocates memory from the heap, and new dynamically allocates memory for objects from the free storage area. The location of the free store depends on the implementation of operator new. The free storage area can be not only a heap, but also a static storage area, depending on where operator new allocates memory for objects.

  • Return type safety : malloc returns void* after memory allocation is successful, and then casts the type to the required type; new operator returns a pointer type that matches the object type after memory allocation is successful; so new is a type-safe operator .

  • Memory allocation failure return value : malloc returns NULL after memory allocation failure. An exception (bac_alloc) will be thrown if new fails to allocate memory.

  • Calculation of the size of the allocated memory : When using the new operator to apply for memory allocation, there is no need to specify the size of the memory block. The compiler will calculate it based on the type information, while malloc needs to explicitly indicate the size of the required memory.

  • Whether it can be overloaded : opeartor new /operator delete can be overloaded. And malloc/free cannot be overloaded.

Which piece of memory is allocated by new

heap

Replenish:

The memory area applied by new is called free storage area in C++. The new/delete of many compilers is implemented based on malloc/free, so free storage is usually implemented through heap implementation. At this time, it can be said that the memory area applied by new is on the heap.

What happens if new memory fails?

A std::bad_alloc exception will be thrown.

Replenish:

If you add the std::nothrow keyword, A* p = new (std::nothrow) A;, new will not throw an exception but will return a null pointer.

Why is the destructor usually made into a virtual function?

If a class has virtual functions, it should define a virtual destructor for it. This is because when the delete operator is used to release a base class pointer pointing to a derived class object, if the destructor of the base class is not a virtual function, only the destructor of the base class will be called, and the destructor of the derived class will not be called. constructor, which can lead to problems with memory leaks and undefined behavior. By defining the destructor as a virtual function, you can ensure that when the derived class object is released, the destructor of the derived class is called first, and then the destructor of the base class is called, thereby avoiding problems of memory leaks and undefined behavior.

What is the difference between thread and process

A process is an execution process of a program in the operating system, which has an independent address space and system resources. A thread is an execution unit in a process, and multiple threads in the same process share the same address space and system resources.

Replenish:

  • A process is the basic unit of resource scheduling. Running an executable program will create one or more processes. A process is an executable program that runs. A thread is the basic unit of program execution. Each process has a unique main thread, and There can only be one, the main thread and the process are interdependent, and the process will also end when the main thread ends.

  • Each process has its own independent address space, which is not shared with other processes; there can be multiple threads in a process, sharing the same address space with each other. Resources such as heap memory, files, and sockets are managed by the process, and multiple threads in the same process can share them. The memory and other resources used by each process are returned to the operating system when the process exits or is killed.

  • Concurrent application development can use multi-process or multi-thread. Multi-threading is more efficient because it can share resources; on the contrary, multi-process (by default) does not share address space and resources, which makes development more troublesome and inefficient when sharing data is required. However, multi-process security is better. When a problem occurs in a certain process, other processes are generally not affected; in the case of multi-threading, if a thread performs an illegal operation, the entire process will exit.

What does an rvalue reference do?

Not used

Replenish:

  • Rvalue reference is a feature introduced by C++11, which refers to a way to reference rvalues. There are two main functions of rvalue references:

  • Move semantics can be achieved via rvalue references. Move semantics can improve code efficiency by transferring resource ownership of an object from one object to another without deep copying.

  • Rvalue references can also be used for perfect forwarding. In a function template, perfect forwarding can be achieved by using formal parameters of rvalue reference type to receive parameters, that is, to keep the value category of the original parameter (lvalue or rvalue), and pass the parameter to another function.

smart pointer

A smart pointer is a special pointer in C++ that is an object that manages the life cycle of the object pointed to by another pointer. Smart pointers can automatically allocate and release memory, avoiding the trouble of manually managing memory and the risk of errors.

The C++ standard library provides three smart pointers:

  • shared_ptr: Multiple smart pointers can share the same object, and when the last pointer is destroyed, it frees the object's memory.

  • unique_ptr: Exclusive smart pointer, cannot share the same object, when the smart pointer is destroyed, it will release the memory of the object.

  • weak_ptr: weak reference smart pointer, which will not increase the reference count of the object, and is used to avoid memory leaks when shared_ptr circular references.

In what scenarios will smart pointers be applied

I am in dynamic memory management myself, using smart pointers can avoid the trouble of manually managing memory and the risk of errors.

If you encounter the problem of memory leak, how do you usually solve it?

Break point location and then do processing

Later, I thought that the other party should want me to answer this kind of treatment⬇️

  • Add necessary error handling codes to the program to avoid memory leaks caused by abnormal conditions in the program.

  • Use RAII mechanisms such as smart pointers to automatically manage memory, avoiding the trouble of manually managing memory and the risk of errors.

  • Use memory analysis tools to detect memory leaks in your program and fix them accordingly.

The default function in the class

no attention

Replenish:

In C++, if a class does not explicitly define "constructor, destructor, copy constructor, assignment operator overloading function", then the compiler will automatically generate these functions, which are called default functions.

What is inside the sort function

The sort function is internally implemented using the quick sort algorithm, and its time complexity is O(nlogn), which is a very efficient sorting algorithm.

The principle of quick sort

  1. Select a datum element.

  2. The elements smaller than or equal to the reference element are moved to the left of the array, and the elements greater than the reference element are moved to the right of the array. This process is called partitioning.

  3. Recursively sort the divided left and right subsequences.

But if you think about it carefully, you can continue to answer⬇️

In the actual implementation, the sort function has some optimizations, such as:

  • When the number of sorted elements is less than a certain threshold, the insertion sort algorithm is used.

  • When there are a large number of repeated elements, use the three-way partition quick sort algorithm.

Why choose quick queue

By default, its distribution is a relatively random distribution, and then it is quickly ranked on a relatively random distribution, with better performance and faster speed

What is a multithreaded lock

Multi-thread lock is a mechanism used to protect shared resources. In multi-threaded programming, if multiple threads access the same shared resource at the same time, a race condition (Race Condition) may occur, resulting in undefined behavior of the program. To prevent this from happening, multithreaded locks can be used to protect shared resources.

The basic idea of ​​a multi-threaded lock is to acquire a lock before accessing a shared resource, and then release the lock after the access is complete. This can ensure that only one thread can access the shared resource at the same time, thereby avoiding the occurrence of race conditions.

Common multithreaded locks include mutexes, read-write locks, condition variables, and more. Among them, mutual exclusion locks are used to protect access to shared resources, read-write locks are used to improve concurrency performance in the case of more reads and fewer writes, and condition variables are used for synchronization and communication between threads.

What is the transaction of mysql

In a database, a transaction (Transaction) is a group of operation units that either all execute successfully or fail to execute. Transaction is one of the important mechanisms to ensure the consistency of the database. It can treat a series of operations as a whole to ensure the integrity and correctness of the database.

Transactions have four properties, namely ACID:

  • Atomicity: All operations in a transaction either succeed or fail, and there will be no partial execution.

  • Consistency: The state of the database before and after the execution of the transaction is consistent, that is, the constraints and rules in the database are maintained.

  • Isolation: When multiple transactions are executed concurrently, they will not affect each other's execution results.

  • Durability: After the transaction execution is completed, the modifications made to the database will be permanently saved in the database.

MySQL is a common relational database that supports transaction mechanisms. In MySQL, transactions can

Managed by using Transaction Control Statements, including the following three statements:

  • START TRANSACTION: Start a transaction.

  • COMMIT: Submit a transaction to make it effective.

  • ROLLBACK: Roll back a transaction to make it invalid.

In MySQL, transactions are disabled by default, and transactions need to be enabled by setting the autocommit parameter to 0. After enabling transactions, you can perform transaction operations by executing SQL statements,

What will happen in the middle of the TCP connection

In a TCP connection, the following operations occur between the client and the server:

  • Handshake phase: The client sends a SYN packet (synchronous packet) to the server, requesting to establish a connection. After receiving the SYN packet, the server sends a SYN+ACK packet (synchronous confirmation packet) to the client, indicating that the connection can be established. After the client receives the SYN+ACK packet, it sends an ACK packet (confirmation packet) to the server, indicating that the connection is established successfully.

  • Data transmission stage: After the connection is successfully established, data transmission can be performed between the client and the server. The client sends a data packet to the server, the server receives the data packet and processes it, and then sends a response packet to the client. After the client receives the response packet, it can send the data packet to the server again, and so on.

  • Disconnect phase: When the client or server no longer needs to connect, it can send a FIN packet (end packet) to request disconnection. After receiving the FIN packet, the other party also sends a FIN packet in response, expressing agreement to disconnect. When both ends receive FIN packets from each other, the connection is truly closed.

It should be noted that packet loss and congestion may occur in the TCP connection, and corresponding processing needs to be performed, such as retransmitting lost data packets, adjusting the size of the sending window, and so on.

algorithm

Reversal of intervals specified in the table

rhetorical question

Department business; Technology stack situation

interview summary

Feel:

  • I feel okay, I basically answered all the face-to-face interviews, and I didn’t ask specific items (because I don’t have any items to ask)

Disadvantages:

  • The basic knowledge of C++ is still not proficient enough

  • Project optimization

Guess you like

Origin blog.csdn.net/bjweimengshu/article/details/130817944