Why uninitialized pointers cause mem access violations close to 0?

给你一囗甜甜゛ 提交于 2019-12-12 11:00:18

问题


It is said that often (but not always) when you get an AV in a memory location close to zero (like $89) you have an uninitialized pointer.
But I have seen this also in Delphi books... Hm... or they have been all written by the same author(s)???


Update:
Quote from "C++ builder 6 developers guide" by Bob Swart et all, page 71:

When the memory address ZZZZZZZZZ is close to zero, the cause is often an uninitialized pointer that has been accessed.

Why is it so? Why uninitialized pointers contain low numbers? Why not big numbers like $FFFFFFF or plain random numbers? Is this urban myth?


回答1:


This is confusing "uninitialized pointers" with null references or null pointers. Access to an object's fields, or indexes into a pointer, will be represented as an offset with respect to the base pointer. If that reference is null then the offsets will generally be addresses either near zero (for positive offsets) or addresses near the maximum value of the native pointer size (for negative offsets).

Access violations at addresses with these characteristic small (or large) values are a good clue that you have a null reference or null pointer, specifically, and not simply an uninitialized pointer. An uninitialized reference can have a null value, but may also have any other value depending on how it is allocated.




回答2:


Why uninitialized pointers contain low numbers?

They don't. They can contain any value.

Why not big numbers like $FFFFFFF?

They can perfectly well contain values like $FFFFFFF.

or plain random numbers?

Uninitialised variables tend not to be truly random. They typically contain whatever happened to have been written to that memory location the last time it was used. For instance, it is very common for uninitialised local variables to contain the same value every time a function is called because the history of stack usage happens to be repeatable.

It's also worth pointing out that random is an often misused word. People often say random when they actually mean distributed randomly with uniform distribution. I expect that's what you meant when you used the term random.




回答3:


Your statement about AV close to zero is true for dereferencing a null pointer. It is zero or close to zero because you either dereference the null pointer:

int* p{};
const auto v = *p; // <-- AV at memory location = 0

or access an array item:

char* p{};
const auto v = p[100]; // <--AV at memory location = 100

or a struct field:

struct Data
{
  int field1;
  int field2;
};

Data* p{};
const auto v = p->field2; // AV at memory location = 4


来源:https://stackoverflow.com/questions/54570303/why-uninitialized-pointers-cause-mem-access-violations-close-to-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!