如何确定c中未初始化的指针指向的目的地? [英] How is the destination that an uninitialized pointer in c points to determined?

查看:240
本文介绍了如何确定c中未初始化的指针指向的目的地?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,如果一个指针在C中声明(并且未初始化),它将指向可能包含任何内容的随机"内存地址.

但是实际指向何处确定呢?大概不是真正随机的,因为这样会导致效率低下和不合逻辑.

解决方案

如果此指针是在所有函数之外定义的(或为static),则在main()获得控制之前,它将被初始化为NULL. /p>

如果此指针是通过malloc(sizeof(sometype*))在堆中创建的,则它将包含在其位置上发生的任何事情.它可以是先前分配和释放的内存缓冲区中的数据.也可以是malloc()free()用于管理可用块和已分配块列表的一些旧控制信息.或者,如果OS(如果有)没有清除程序的内存,或者如果系统调用的内存分配返回未初始化的内存,则可能是垃圾,因此这些内存可能包含以前运行的程序的代码/数据,或者仅包含RAM芯片在运行时产生的一些垃圾.系统已启动.

如果此指针在函数本地(而不是static),则它将包含堆栈中已放置的任何内容.或者,如果将CPU寄存器分配给该指针而不是存储单元,它将包含前面的指令在该寄存器中留下的任何值.

所以,它不会是完全随机的,但是您在这里几乎没有完全控制权.

I know that if a pointer is declared in C (and not initialized), it will be pointing to a "random" memory address which could contain anything.

How is where it actually points to determined though? Presumably it's not truly random, since this would be inefficient and illogical.

解决方案

If this pointer is defined outside of all functions (or is static), it will be initialized to NULL before main() gets control.

If this pointer is created in the heap via malloc(sizeof(sometype*)), it will contain whatever happens to be at its location. It can be the data from the previously allocated and freed buffer of memory. Or it can be some old control information that malloc() and free() use to manage the lists of the free and allocated blocks. Or it can be garbage if the OS (if any) does not clear program's memory or if its system calls for memory allocation return uninitialized memory and so those can contain code/data from previously run programs or just some garbage that your RAM chips had when the system was powered on.

If this pointer is local to a function (and is not static), it will contain whatever has been at its place on the stack. Or if a CPU register is allocated to this pointer instead of a memory cell, it will contain whatever value the preceding instructions have left in this register.

So, it won't be totally random, but you rarely have full control here.

这篇关于如何确定c中未初始化的指针指向的目的地?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆