SoFunction
Updated on 2025-04-06

The difference between a wild pointer and a null pointer in C language

Wild pointer

definition

A wild pointer refers to a pointer variable that points to an unknown, random, incorrect, or has been released memory address. They may point to a temporary variable on the program stack (that variable may have been out of the stack and overwritten), or to afreeordeleteThe freed memory block, or simply a random, uninitialized memory address.
Note: The wild pointer will not directly raise an error, and there will be problems with the memory area pointed to by the wild pointer.

use

(In fact, wild pointers should be avoided):
Wild pointers are usually caused by programming errors, such as forgetting to initialize the pointer, and not setting the pointer to after freeing memory.NULLwait. Because the memory state they point to is uncertain, using wild pointers often leads to serious problems such as program crashes, data corruption, etc.

principle

The generation of wild pointers is often related to improper memory management. In C language, memory management needs to be managed manually (including allocation and release). If negligence occurs in this process, it may lead to the generation of wild pointers.

Pointer not initialized

In C, pointer variables are not automatically initialized toNULLor any other value. If a valid memory address is not assigned to it immediately after declaring a pointer or explicitly initializes it toNULL, then this pointer will contain a random memory address and become a wild pointer.

int *ptr; // A pointer variable ptr is declared, but not initialized*ptr = 10; // Try to decimateptr,This is undefined behavior,becauseptrIt's a wild pointer

Pointer outbound access

When a pointer is used to access an array or other contiguous memory area, if the accessed index exceeds its valid range, the pointer points to an unknown memory address, thus becoming a wild pointer.

int arr[10];  
int *ptr = arr;  
for (int i = 0; i <= 12; i++) { // Pay attention to loop conditions, i will exceed the range of the array    *(ptr + i) = i; // When i=10 and i=11, ptr+i becomes a wild pointer}

NULL is not set after freeing memory

usefreeordeleteAfter the function releases the memory pointed to by the pointer, if the pointer is not set toNULL, then this pointer will still retain the original memory address. At this point, if the program continues to try to access memory through the pointer (although the memory may have been reassigned to other variables by the system), undefined behavior will result in because the pointer has become a wild pointer.

int *ptr = (int*)malloc(sizeof(int));  
if (ptr != NULL) {  
    *ptr = 10;  
    free(ptr); // Free memory    // Forgot to set ptr to NULL    // ...  
    // If you use ptr again later, such as *ptr = 20; then ptr is a wild pointer}

Return the address of the local variable

In a function, if a pointer to a local variable is returned, the local variable will be destroyed after the function returns, but the returned pointer still points to the memory address that has been destroyed. At this time, the pointer becomes a wild pointer.

int* getPointer() {  
    int local = 10;  
    return &local; // Return a pointer to a local variable}  
  
int main() {  
    int *ptr = getPointer(); // ptr becomes a wild pointer because local has been destroyed    // ...  
}

Pointer operation error

When performing pointer operations (such as pointer addition, subtraction, increment, decrement), if the operation result exceeds the legal memory range, the pointer will point to an unknown memory address, thus becoming a wild pointer.

How to avoid it

Initialize pointer

When declaring a pointer variable, it should be initialized immediately toNULLOr point to a valid memory address. This prevents the pointer from being used without initialization, thereby avoiding the generation of wild pointers. The pointer variable will not automatically become a NULL pointer when it is created. Its default value israndomof,The space it refers to is random.

int *ptr = NULL; // Initialize to NULLint array[10];  
int *arrayPtr = array; // Point to the home address of a valid array

Check if the pointer is NULL

Always check if it isNULL. This ensures that dereferences are performed only when the pointer points to a valid memory address.

if (ptr != NULL) {  
    *ptr = 10; // Dereference only if ptr is not NULL}

Release memory NULL

After freeing the memory pointed to by the pointer, the pointer should be set toNULL. This prevents incorrectly trying to dereference the pointer again in subsequent code.

free(ptr);  
ptr = NULL; // Avoid becoming a wild pointer

Avoid returning local variable addresses

Local variables defined inside a function are destroyed when the function returns, so a pointer to these local variables should not be returned. If you need to return data, consider returning a copy of the data, using dynamically allocated memory, or passing pointers through parameters and allocating memory outside the function.

// Counterexampleint* badFunction() {  
    int local = 10;  
    return &local; // Return a pointer to a local variable, which may cause a wild pointer}  

// Example one: Return dynamically allocated memoryint* goodFunction() {  
    int *ptr = (int*)malloc(sizeof(int));  
    if (ptr != NULL) {  
        *ptr = 10;  
    }  
    return ptr; // Note: The caller needs to be responsible for freeing the memory}

Using smart pointers (C++ only)

usestd::unique_ptrstd::shared_ptrSmart pointers can automatically manage the life cycle of memory, thereby reducing the risk of wild pointers.

Pay attention to pointer operation

When performing pointer operations (such as increment, decrement, addition, subtraction), make sure that the pointer is always within the legal range. Avoid pointer access from out-of-bounds, which may lead to the appearance of wild pointers (although not direct wild pointers, but may lead to unpredictable behavior).

Code review and testing

Use tools such as static analysis tools, memory leak detectors, and unit testing.

Empty pointer

definition

A null pointer is a special pointer value that does not point to any valid memory address. In C, null pointers are usually made of macrosNULLTo show that, in factNULLUsually defined as((void*)0)Or simply0

use

A null pointer is mainly used to indicate that the pointer does not currently point to any object. When initializing the pointer, set it toNULLIt can be explicitly stated that the pointer does not currently point to any valid memory address. In addition, after freeing the memory pointed to by the pointer, set the pointer toNULLIt can prevent the generation of wild pointers.

principle

The principle of a null pointer is simple, it is a special value (usually 0) that means that the pointer does not point to any memory address. In C, any attempt to dereference a null pointer is undefined and usually causes a program to crash.

For example:

#include <>  
  
int main() {  
    int *ptr = NULL; // Declare a pointer variable ptr and initialize it to NULL, indicating that it does not point to any memory address  
    if (ptr != NULL) {  
        // If ptr is not NULL, execute the code here (but in this example, the code here will not be executed)    } else {  
        printf("ptr is NULL\n"); // Output information that ptr is a null pointer    }  
  
    // Try to dereference ptr (this is unsafe because ptr is NULL)    // *ptr = 10; // This will cause undefined behavior because ptr is a null pointer  
    return 0;  
}

In the above example,ptrInitialized asNULL, means it does not point to any memory address. Then, we passifStatement checkptrWhetherNULL, and print the corresponding information based on the results. Note that we did not try to dereferenceptr, because this is a null pointer, dereference is not safe.

This is the end of this article about the difference between wild pointers and empty pointers in C language. For more related C language content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!