Wild Pointers

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.

Dangling Pointers

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.

Example: After free()

int *ptr = (int *) malloc(sizeof(int));
*ptr = 42;
free(ptr);     // Memory freed
*ptr = 50;     // Dangling pointer usage - undefined

Example: Local Scope

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.

Memory Leaks

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.

Example: Forgotten free()

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.