Click the above“Beginner’s Guide to Vision” to selectStarred or “Top”
Essential knowledge delivered promptly
Essential knowledge delivered promptly
Pointers in C/C++ provide programmers with more flexibility, but they are also a double-edged sword. If not used properly, they can lead to various problems in your programs. Some say that C/C++ programmers spend half of their time dealing with bugs caused by pointers, which highlights how terrifying the traps within pointers can be. Therefore, we must be vigilant while writing code.
To avoid pointer-related issues in code, we need to understand what problems can arise from improper pointer usage and how to avoid them. Let’s summarize the common issues encountered when using pointers.
Avoid Memory Leaks
Programs require memory during execution, and we know that memory is limited; it is a precious resource for computers. For memory that has been used, it should be promptly returned to the operating system.
In C/C++, if it’s memory on the stack (such as local non-static variables in a function), the operating system will automatically reclaim it after use. However, if it’s memory allocated dynamically on the heap, we need to manually release it.
If we forget to release this dynamic memory in our program while it runs as a persistent service process, it will lead to increasing memory usage, which can severely impact system performance or even cause process crashes.
In short, failing to release memory that is no longer needed is called a memory leak, and memory leaks are a serious issue. Now, let’s look at a few cases of memory leaks.
In C/C++, dynamically allocated memory using functions like malloc or the new operator must be manually released after use; otherwise, it will cause memory leaks.

Suggestion: Pay attention to using malloc/free and new/delete in pairs when writing code
Even if free/delete is explicitly called after malloc/new to release memory, exceptions can occur that prevent the free/delete statements from executing, leading to memory leaks, as shown in the following example.


From the results, it can be observed that the class destructor was not executed, indicating that the delete statement was not executed.
Some might say, “This is simple; just add a delete t after the cout in the catch statement, and it will work, right?”
That’s true, but this is just a small test program with a few dozen lines of code, and you might spot the issue immediately. However, when faced with a large project, you would likely feel overwhelmed. A better solution to such problems is to use smart pointers, which will be covered in a dedicated article later.
Suggestion: Pay more attention to using smart pointers in C++ code
Avoid Wild Pointers
A wild pointer, also known as a dangling pointer, refers to a pointer that points to “garbage” memory. Using a wild pointer can cause unpredictable behavior in the program.
Note that a wild pointer is not a NULL pointer; it is more prone to errors than a NULL pointer because it cannot be prevented by a condition like if (NULL == p). We must be cautious when writing code.
For example, if pointer p is freed or deleted but not set to NULL, it may mislead one to think p is a valid pointer. In reality, free or delete only releases the memory pointed to, but the pointer still holds the address of that memory, which has been reclaimed and can no longer be used by the process. The following example illustrates a typical case of using a wild pointer.


Suggestion: Set the corresponding pointer to NULL after free or delete
When creating pointer variable p, if it is not initialized, p will hold a random garbage value. Reading or writing to this pointer is dangerous and can cause unpredictable behavior in the program.


Suggestion: Always initialize pointer variables, even if it is just to NULL.
In C/C++, local variables are stored on the stack, which means they are created when a function is called and destroyed when the function ends. Therefore, returning the address of a local variable to a pointer after it has been reclaimed is also a case of a wild pointer.
Consider the following example: the intention is to return the address of variable i from function fun to p, allowing access to this variable through p. However, printing *p shows 32767 instead of the value of i, which is 8. Bugs like this can be difficult to locate in large projects.


Suggestion: Do not return the address of a local variable from a function. If the logic of the code requires returning the address of a local variable, that local variable must be declared as static, as static variables persist for the entire duration of the program.
Avoid Using NULL Pointers
Everyone knows that NULL pointers should not be used in programs, but if not careful, NULL pointers can still be unintentionally used in your code. Let’s look at two examples that are prone to issues.
When a dynamic memory allocation function allocates memory, it may fail and return NULL.


From the program’s output, if malloc fails and returns NULL assigned to p, accessing the memory at address 0 through p will result in a “Segmentation fault” error.
Suggestion: When using memory allocation functions, always check with if(p==NULL) or if(p!=NULL) for error handling.
Moreover, functions with pointer parameters may also inadvertently use NULL pointers. If a NULL pointer is passed when calling such a function and there is no if(p!=NULL) check, it can lead to significant issues later when using the pointer, as shown in the following example.


Suggestion: For functions with pointer parameters, always perform error checking at the function entry with if(p==NULL) or if(p!=NULL).
Good news!
The Beginner's Guide to Vision knowledge community is now open to the public👇👇👇
Download 1: OpenCV-Contrib Module Chinese Tutorial
Reply "Chinese Tutorial for Extension Modules" in the backend of the "Beginner's Guide to Vision" public account to download the first Chinese version of the OpenCV extension module tutorial, covering installation of extension modules, SFM algorithms, stereo vision, object tracking, biological vision, super-resolution processing, and more than twenty chapters of content.
Download 2: Python Vision Practical Project 52 Lectures
Reply "Python Vision Practical Project" in the backend of the "Beginner's Guide to Vision" public account to download 31 vision practical projects, including image segmentation, mask detection, lane line detection, vehicle counting, adding eyeliner, license plate recognition, character recognition, emotion detection, text content extraction, face recognition, etc., to help quickly learn computer vision.
Download 3: OpenCV Practical Project 20 Lectures
Reply "OpenCV Practical Project 20 Lectures" in the backend of the "Beginner's Guide to Vision" public account to download 20 practical projects based on OpenCV, facilitating advanced learning of OpenCV.
Group Chat
Welcome to join the reader group of the public account to communicate with peers. Currently, there are WeChat groups for SLAM, 3D vision, sensors, autonomous driving, computational photography, detection, segmentation, recognition, medical imaging, GAN, algorithm competitions, etc. (these will be gradually subdivided). Please scan the WeChat ID below to join the group, and note: "Nickname + School/Company + Research Direction", for example: "Zhang San + Shanghai Jiao Tong University + Vision SLAM". Please follow the format; otherwise, you will not be approved. After adding successfully, you will be invited to the relevant WeChat group based on your research direction. Please do not send advertisements in the group; otherwise, you will be removed. Thank you for your understanding~