Search code examples
cpointersdangling-pointer

Dangling pointers in C


When a pointer is allocated memory using malloc, pointer (say x)will now point to memory address. Later I free this(x) memory pointer,but pointer is still pointing to it's old memory. This would now create dangling pointer. (Because I did not point the old pointer to NULL after free)

Now, assume I use malloc and assume new pointer(y) now points to same memory location as old pointer (x) Doesn't memsetting new pointer (y) to 0 solve dangling pointer issue.

Assume I have only one struct type.So every malloc which I do is always of same size of same structure. If it was different struct , I know i may still have some data at the end of struct if new pointer (y) has small memory allocation than pointer (x)


Solution

  • The term dangling pointer means that whatever address in memory it points to is invalid. If you make it valid, like your 2nd malloc, then the address becomes valid. If you store the same address in two different variables (via your assumption) both are valid pointers:

    #include <stdio.h>
    #include <stdlib.h>
    
    
    struct s { int i; };
    
    
    int main() {
        struct s *p = malloc(sizeof(struct s));
        printf("before: %p\n", (void *) p);
        free(p);
        // p is dangling
        printf("after:  %p\n", p);
    
        struct s *p2 = malloc(sizeof(struct s));
        // p and p2 are valid
        printf("before: %p\n", (void *) p2);
        free(p2);
        // p and p2 are dangling
        printf("after:  %p\n", p2);
    }
    

    and the output from my pleasingly corroborative malloc:

    before: 0x561b73d3b260
    after:  0x561b73d3b260
    before: 0x561b73d3b260
    after:  0x561b73d3b260