zoukankan      html  css  js  c++  java
  • 什么是野指针?(What is a wild pointer?)

    未被初始化的变量称为野指针(wild pointer)。顾名思义,我们不知道这个指针指向内存中的什么地址,使用不当程序会产生各种各样的问题。

    理解下面的例子:

    int main()
    {
        int *p;  // wild pointer, some unknown memory location is pointed
     
        *p = 12; // Some unknown memory location is being changed
     
        // This should never be done.
    }

    要注意的是,如果指针指向已知的变量就不是野指针。下面的代码中指针p在指向变量a之前一直是野指针。

    int main()
    {
        int  *p; // wild pointer, some unknown memory is pointed
        int a = 10;
     
        p = &a;  // p is not a wild pointer now, since we know where p is pointing
     
        *p = 12; // This is fine. Value of a is changed
    }

    如果我们需要指向一个没有变量名的值,我们应该给这个值分配内存,将这个值放在分配的内存中。

    int main()
    {
        //malloc returns NULL if no free memory was found
        int *p = malloc(sizeof(int));
     
        //now we should check if memory was allocated or not
        if(p != NULL)
        {
            *p = 12; // This is fine (because malloc doesn't return NULL)
        }
        else
        {
            printf("MEMORY LIMIT REACHED");
        }
    }
  • 相关阅读:
    错题
    URL和URI区别
    适配器
    JAVA 反射机制
    JAVA 面试题
    JAVA 继承
    多态 JAVA
    Java面向对象编辑
    [LeetCode] Merge k Sorted Lists
    [LeetCode] Valid Palindrome
  • 原文地址:https://www.cnblogs.com/programnote/p/4721223.html
Copyright © 2011-2022 走看看