什么是野指针?(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"); } }
Copyright © 2015 programnote
分类:
Algorithms
标签:
theory
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 为什么构造函数需要尽可能的简单
· 探秘 MySQL 索引底层原理,解锁数据库优化的关键密码(下)
· 大模型 Token 究竟是啥:图解大模型Token
· 35岁程序员的中年求职记:四次碰壁后的深度反思
· 继承的思维:从思维模式到架构设计的深度解析
· 基于Docker+DeepSeek+Dify :搭建企业级本地私有化知识库超详细教程
· 由 MCP 官方推出的 C# SDK,使 .NET 应用程序、服务和库能够快速实现与 MCP 客户端
· 电商平台中订单未支付过期如何实现自动关单?
· 上周热点回顾(3.31-4.6)
· 用 .NET NativeAOT 构建完全 distroless 的静态链接应用