A wild pointer is an uninitialized pointer. It points to a random memory location, which can lead to unpredictable behavior or crashes. Always initialize pointers before using them.
int *ptr; // Wild pointer
*ptr = 10; // Undefined behavior
Fix this by initializing the pointer with NULL or a valid address.
A dangling pointer points to memory that has been freed or goes out of scope. Using such a pointer after the memory is invalid can cause errors or crashes.
int *ptr = (int *) malloc(sizeof(int));
*ptr = 42;
free(ptr); // Memory freed
*ptr = 50; // Dangling pointer usage - undefined
int* getPtr() {
int x = 10;
return &x; // Returning address of local variable - dangerous
}
To avoid this, set pointers to NULL after freeing or use dynamic allocation for returned data.
A memory leak happens when dynamically allocated memory is not released using free(). The memory remains occupied even after it's no longer needed, eventually exhausting system memory.
void leak() {
int *data = (int *) malloc(100 * sizeof(int));
// Memory not freed - leak!
}
Always pair every malloc, calloc, or realloc with free when the memory is no longer needed.