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 */
  • 相关阅读:
    ios学习笔记——UIScrollView
    ios设计模式——单例模式
    ios设计模式——生成器模式
    ios学习笔记——UITableView
    ios 第3天
    ios 第2天
    ios入门第一天
    ios 运行时特征,动态改变控件字体大小
    ios 修改导航栏返回按钮的图片
    ios 在工程中使用字体
  • 原文地址:https://www.cnblogs.com/JasperZhao/p/12915627.html
Copyright © 2011-2022 走看看