1

I have an array of int pointers.

int *ints[3];

What happens to memory when this array is defined? What would be the initial pointer values stored? When I try to dereference a value, I get a segmentation fault which tells me the values are arbitrary.

0

1 Answer 1

4

It depends on the storage of the array.

  • If it has static storage, i.e. declared outside of any function or declared with static in a function, then all the elements will be NULL

  • If it is declared in a function, without static, it will have automatic storage and the initial values will be indeterminate

The standard happens to be quite clear and helpful in this matter:

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:

  • if it has pointer type, it is initialized to a null pointer;
  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;
  • if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero
    bits;
Sign up to request clarification or add additional context in comments.

2 Comments

I believe it should be noted that "indeterminate" is not the same as "random". The distinction may be less significant for pointers, because using a random pointer is just as much a problem as using an indeterminate pointer, but for number types on hardware that supports trap representations, "random" can imply "any valid value", whereas an indeterminate value may be a trap representation.
It is as significant to pointers as for integer types. What traps are for integers are misaligned values for pointers. Even if by chance a pointer pointed into valid memory, it could still raise a signal when accessing the object if it isn't aligned for the base type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.