Why uninitialized pointers cause mem access violat

2019-06-21 11:50发布

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?

3条回答
三岁会撩人
2楼-- · 2019-06-21 12:19

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.

查看更多
Anthone
3楼-- · 2019-06-21 12:20

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
查看更多
趁早两清
4楼-- · 2019-06-21 12:23

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.

查看更多
登录 后发表回答