directory

1. Wild Pointer

2. Dangling Pointer


1. Wild Pointer

Wild Pointer: a pointer that has not been initialized and is not sure what the pointer points to. For example:

void *p;  // when p is a wild pointer
Copy the code

Because the “wild pointer” can point to any memory segment, it can corrupt normal data and cause other unknown errors. In the actual C language program development, when defining Pointers, it is generally necessary to avoid the appearance of “wild Pointers”, which can be solved by assigning initial values:

void *p = NULL;
void *data = malloc(size);
Copy the code

2.”Dangling Pointers“(dangling pointer)

Dangling pointer A pointer to which the original memory to which it was referred has been removed. A pointer to a block of memory is a “dangling pointer” if the memory is later reclaimed (freed) by the operating system, but the pointer still points to the block. For example:

void *p = malloc(size);
assert(p);
free(p); 
// now p is "dangling pointer"
Copy the code

“Dangling Pointers” in C can cause unpredictable errors that are difficult to locate once they occur. This is because after free(p), the p pointer still points to the previously allocated memory, and using p later does not raise an error if the memory is temporarily accessible to the program without causing conflicts.

Therefore, in the actual PROGRAM development of C language, in order to avoid unpredictable errors caused by “dangling pointer”, pointer P is often assigned NULL after memory is freed:

void *p = malloc(size);
assert(p);
free(p); 
// Avoid dangling Pointers
p = NULL;
Copy the code