Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the destination that an uninitialized pointer in c points to determined?

Tags:

c

pointers

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.

like image 893
user2282497 Avatar asked Apr 15 '13 12:04

user2282497


People also ask

What does an uninitialized pointer point to in C?

The pointer p is uninitialized and points to a random location in memory when you declare it. It could be pointing into the system stack, or the global variables, or into the program's code space, or into the operating system.

What happens if you dereference an uninitialized pointer?

For an uninitialized function pointer that has a non-zero value, the dereference can cause an exception to occur. This happens if the storage that the uninitialized pointer points to is read-protected. Usually, comparing uninitialized function pointers results in undefined behavior.

Are uninitialized pointers Nullptr?

A null pointer should not be confused with an uninitialized pointer: a null pointer is guaranteed to compare unequal to any pointer that points to a valid object. However, depending on the language and implementation, an uninitialized pointer may not have any such guarantee.

What is an Uninitialised pointer?

An uninitialized pointer stores an undefined value. A null pointer stores a defined value, but one that is defined by the environment to not be a valid address for any member or object.


1 Answers

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.

like image 72
Alexey Frunze Avatar answered Oct 14 '22 02:10

Alexey Frunze