zoukankan      html  css  js  c++  java
  • What is Dangling Pointer with Cause and How to avoid it?

    Dangling pointers in computer programming are pointers that pointing to a memory location that has been deleted (or freed).

    Cause of dangling pointers

    1. Return Local Variable in Function Call

    #include<stdio.h>
    #include<string.h>
    
    char *getHello()
    {
        char str[10];
        strcpy(str,"Hello!");
        return(str);
    }
    
    int main()
    {
        //str falls out of scope
        //function call char *getHello() is now a dangling pointer 
        printf("%s", getHello());
    }


    2. Variable goes Out of Scope

    #include<stdio.h>
    
    int main()
    {
        char **strPtr;
        {
            char *str = "Hello!";
            strPtr = &str;
        }
        // str falls out of scope 
        // strPtr is now a dangling pointer 
        printf("%s", *strPtr);
    }


    3. De-allocating or free variable memory

    #include<stdio.h>
    #include<stdlib.h>
    
    int main()
    {
        char **strPtr;
        char *str = "Hello!";
    	
        strPtr = &str;
        free(str);
        //strPtr now becomes a dangling pointer
    	
        printf("%s", *strPtr);
    }

    Avoiding dangling pointer errors

    We can avoid the dangling pointer errors by initialize pointer to NULL, after de-allocating memory, so that pointer will be no longer dangling. Assigning NULL value means pointer is not pointing to any memory location.

    char **strPtr;
    char *str = "Hello!";
    	
    strPtr = &str;
    
    free (str);  /* strPtr now becomes a dangling pointer */
    ptr = NULL;   /* strPtr is no more dangling pointer */
  • 相关阅读:
    常见DOS命令
    前台传参到后台出现中文乱码问题
    Servlet.init() for servlet [spring-dispatcher] threw exception
    ES6-2
    ES6语法(一)
    JS区分对象类型
    ko数组
    sortable的基本属性
    MUI消息推送
    target和currentTarget
  • 原文地址:https://www.cnblogs.com/JasperZhao/p/12915627.html
Copyright © 2011-2022 走看看