什么是野指针?(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");
    }
}
复制代码
posted @   programnote  阅读(840)  评论(0编辑  收藏  举报
编辑推荐:
· 为什么构造函数需要尽可能的简单
· 探秘 MySQL 索引底层原理,解锁数据库优化的关键密码(下)
· 大模型 Token 究竟是啥:图解大模型Token
· 35岁程序员的中年求职记:四次碰壁后的深度反思
· 继承的思维:从思维模式到架构设计的深度解析
阅读排行:
· 基于Docker+DeepSeek+Dify :搭建企业级本地私有化知识库超详细教程
· 由 MCP 官方推出的 C# SDK,使 .NET 应用程序、服务和库能够快速实现与 MCP 客户端
· 电商平台中订单未支付过期如何实现自动关单?
· 上周热点回顾(3.31-4.6)
· 用 .NET NativeAOT 构建完全 distroless 的静态链接应用
点击右上角即可分享
微信分享提示