Incorrect example:
void EraseMapItem1(int key)
{
appRunningRecordMap_.erase(key);
} When one thread is deleting elements of a map container, another thread operates on the same map at the same time, it will cause crash.
Correct example:
void EraseMapItem2(int key)
{
// Lock.
std::lock_guard<std::mutex> lock(mutex_);
appRunningRecordMap_.erase(key);
}
void FindMapItem(int key)
{
// Lock.
std::lock_guard<std::mutex> lock(mutex_);
appRunningRecordMap_.find(key);
} Incorrect example:
std::list<std::shared_ptr<Object>> g_list;
void MainFunc()
{
auto xxx = std::make_shared<Object>();
g_list.push_back(xxx);
}
// Thread 1
void Thread1Func()
{
for (auto &ptr : g_list) {
ptr->method();
}
}
// Thread 2
void Thread2Func()
{
g_list.clear(); // Clearing the list may cause thread 1 to crash when using g_list.
} Correct example:
// Thread 1
void Thread1FuncEx()
{
std::lock_guard<std::mutex> lock(mutexEx_);
for (auto &ptr : g_list) {
ptr->method();
}
}
// Thread 2
void Thread2FuncEx()
{
std::lock_guard<std::mutex> lock(mutexEx_);
g_list.clear();
} Incorrect example:
void Checker::Detection(std::string& url)
{
handler.PostAsyncTask(
[this, &url]() {
if (!Checker::DoCheck(url)) {
// ...
}
}
);
// The url variable is about to be destructed.
}
bool Checker::DoCheck(const std::string& url)
{
// ...
return true;
} Correct example:
void Checker::Detection2(std::string& url)
{
handler.PostAsyncTask(
[this, url]() {
if (!Checker::DoCheck(url)) {
// ...
}
}
);
// The url variable is about to be destructed, but the lambda already has its own copy.
} Incorrect example:
std::shared_ptr<Object> smartPointer = nullptr; smartPointer->method();
Correct example:
std::shared_ptr<Object> smartPointer = nullptr;
if (smartPointer != nullptr) {
smartPointer->method();
} Incorrect example:
Object* xxx = new Object(); std::shared_ptr<Object> xxx1(xxx); // When the reference count of xxx1 is reduced to 0, xxx is destructed once. std::shared_ptr<Object> xxx2(xxx); // When the reference count of xxx2 is reduced to 0, xxx is destructed once.
Correct example:
std::shared_ptr<Object> xxx = std::make_shared<Object>();
Incorrect example:
auto smartPointer = std::make_shared<Object>(); // smartPointer is destructed when its reference count is reduced to 0. auto pointer = smartPointer.get(); pointer->method(); // A crash may occur if pointer is used after smartPinter is destructed.
Correct example:
auto smartPointer = std::make_shared<Object>(); smartPointer->method();
Incorrect example:
Object* pointer = new Object(); std::shared_ptr<Object> smartPointer(pointer); // smartPointer is destructed when its reference count is reduced to 0. pointer->method(); // A crash may occur if pointer is used after smartPointer is destructed. delete pointer; // A crash occurs when the raw pointer is proactively released.
Correct example:
auto smartPointer = std::make_shared<Object>(); smartPointer->method();
Incorrect example:
static void SignalHandler(int signo, siginfo_t* si, void* context) // Signal handling function
{
char *c = (char*)malloc(10); // Do not use malloc, which is a non-asynchronous-safe function.
} Correct example:
static void SignalHandlerEx(int signo, siginfo_t* si, void* context) // Signal handling function
{
char c[10] = {0};
}
Ensure that the objects or functions directly or indirectly called by the signal handling function are asynchronous safe.
malloc is a non-asynchronous-safe function. Therefore, in the signal handling function:
Asynchronous-safe functions
If a function can be securely called and also securely used in a signal handler, the function is asynchronous-safe or asynchronous-signal-safe. The following table lists asynchronous-safe functions, referenced from POSIX standards. Apps can call asynchronous-safe functions in signal handlers.
_Exit() | fexecve() | posix_trace_event() | sigprocmask() |
_exit() | fork() | pselect() | sigqueue() |
abort() | fstat() | pthread_kill() | sigset() |
accept() | fstatat() | pthread_self() | sigsuspend() |
access() | fsync() | pthread_sigmask() | sleep() |
aio_error() | ftruncate() | raise() | sockatmark() |
aio_return() | futimens() | read() | socket() |
aio_suspend() | getegid() | readlink() | socketpair() |
alarm() | geteuid() | readlinkat() | stat() |
bind() | getgid() | recv() | symlink() |
cfgetispeed() | getgroups() | recvfrom() | symlinkat() |
cfgetospeed() | getpeername() | recvmsg() | tcdrain() |
cfsetispeed() | getpgrp() | rename() | tcflow() |
cfsetospeed() | getpid() | renameat() | tcflush() |
chdir() | getppid() | rmdir() | tcgetattr() |
chmod() | getsockname() | select() | tcgetpgrp() |
chown() | getsockopt() | sem_post() | tcsendbreak() |
clock_gettime() | getuid() | send() | tcsetattr() |
close() | kill() | sendmsg() | tcsetpgrp() |
connect() | link() | sendto() | time() |
creat() | linkat() | setgid() | timer_getoverrun() |
dup() | listen() | setpgid() | timer_gettime() |
dup2() | lseek() | setsid() | timer_settime() |
execl() | lstat() | setsockopt() | times() |
execle() | mkdir() | setuid() | umask() |
execv() | mkdirat() | shutdown() | uname() |
execve() | mkfifo() | sigaction() | unlink() |
faccessat() | mkfifoat() | sigaddset() | unlinkat() |
fchdir() | mknod() | sigdelset() | utime() |
fchmod() | mknodat() | sigemptyset() | utimensat() |
fchmodat() | open() | sigfillset() | utimes() |
fchown() | openat() | sigismember() | wait() |
fchownat() | pause() | signal() | waitpid() |
fcntl() | pipe() | sigpause() | write() |
fdatasync() | poll() | sigpending() |
It is dangerous to pass the this pointer to other modules or threads. If the lifetime of other modules or threads is inconsistent with that of the object to which the this pointer points, a crash may occur.
Incorrect example:
void Object1::Run()
{
startThread_ = std::shared_ptr<std::thread>(new std::thread([this] { // Pass the this pointer to another thread.
if (this == nullptr) {
return;
}
this->GetInfo();
// ...
}));
// ...
} Correct example:
class Object2 : public std::enable_shared_from_this<Object2> {
public:
void Run();
void GetInfo() {}
// ...
private:
std::shared_ptr<std::thread> startThread_;
// ...
};
void Object2::Run()
{
std::weak_ptr<Object2> weakPtr = shared_from_this(); // Call shared_from_this to capture this. (weak_from_this can be used since C++17.)
startThread_ = std::shared_ptr<std::thread>(new std::thread([weakPtr] { // Pass weakPtr to another thread.
auto ptr = weakPtr.lock();
if (ptr == nullptr) {
return;
}
ptr->GetInfo();
// ...
}));
// ...
}
void MainFuncEx()
{
auto object = std::make_shared<Object2>(); // The smart pointer must be used to initialize the object.
object->Run();
} Incorrect example:
std::string& GetString()
{
std::string result = "this is string";
return result; // Do not return the reference to the local variable result.
} Correct example:
std::string GetStringEx()
{
std::string result = "this is string";
return result; // Return the value of the local variable.
}